How can I add precision to drand48() in C++? I am using it in a function like:
double x = drand48()%1000+1;
to generate numbers below 1000. But then I get this error:
error: invalid operands of types ‘double’ and ‘int’ to binary ‘operator%’
This does not happen when I use:
double x = rand()%1000+1;
Why and what is the difference between rand() and drand48()?
drand48
returns a number from the interval [0.0, 1.0)
. Are you looking for a number between 1 and 1000? In this case, you need to multiply by 999 and add 1.
Actually, what are you expecting?
drand48()
returns a double
, whereas rand()
returns int
.
Furthermore, drand48()
returns a value that's distributed between [0.0, 1.0)
, so your formula needs to change:
double x = drand48() * 1000.0 + 1; // floating-point values from [1, 1001)
or
double x = (int)(drand48() * 1000.0) + 1; // integer values from [1, 1000]
You could either scale the result of drand48()
as above, or use lrand48()
with your existing formula.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With