implementation of drand48() as given in steve summit's book

P

pereges

I just tried to write a small program based on it :


#include <stdio.h>
#include <stdlib.h>

#define PRECISION 2.82e14

double drand48(void)
{
double x = 0;
double denom = RAND_MAX + 1;
double need;

for(need = PRECISION; need > 1; need /= (RAND_MAX + 1.))
{
x += rand()/denom;
denom *= RAND_MAX + 1. ;
}

return x;

}


int main(void)
{
double x;
x = drand48();
printf("%f" ,x);
x = drand48();
printf("%f", x);

return 0;

}


But each time I get the same output 0. What could be wrong here ?
Does it mean that this will give teh same values over and over again
everytime its called ?
 
J

jacob navia

pereges said:
I just tried to write a small program based on it :


#include <stdio.h>
#include <stdlib.h>

#define PRECISION 2.82e14

double drand48(void)
{
double x = 0;
double denom = RAND_MAX + 1;
double need;

for(need = PRECISION; need > 1; need /= (RAND_MAX + 1.))
{
x += rand()/denom;
denom *= RAND_MAX + 1. ;
}

return x;

}


int main(void)
{
double x;
x = drand48();
printf("%f" ,x);
x = drand48();
printf("%f", x);

return 0;

}


But each time I get the same output 0. What could be wrong here ?
Does it mean that this will give teh same values over and over again
everytime its called ?

Using lcc-win I obtain

0.001268 0.585006

Of course I inserted a space after the first number.
It seems to be working
 
B

Barry Schwarz

I just tried to write a small program based on it :


#include <stdio.h>
#include <stdlib.h>

#define PRECISION 2.82e14

double drand48(void)
{
double x = 0;
double denom = RAND_MAX + 1;
double need;

for(need = PRECISION; need > 1; need /= (RAND_MAX + 1.))
{
x += rand()/denom;
denom *= RAND_MAX + 1. ;
}

return x;

}


int main(void)
{
double x;
x = drand48();
printf("%f" ,x);
x = drand48();
printf("%f", x);

return 0;

}


But each time I get the same output 0. What could be wrong here ?

That's not the result I get. Did you cut and paste your code or
retype it?
Does it mean that this will give teh same values over and over again
everytime its called ?

Since your loop always executes the same number of times (four), the
return value is determined completely by the sequence of values
returned by rand. If you force rand to return the same sequence (such
as by calling srand with the same seed before each call to your
function), then you will get the same value each time. Otherwise not.

As it is now, since you don't call srand at all, your code will
produce the same sequence each time the program is run.


Remove del for email
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,444
Messages
2,571,709
Members
48,796
Latest member
Greg L.
Top