Accuracy for drand48

How to add precision to drand48 () in C ++? I use 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 ()?

+4
source share
3 answers

drand48 returns double in the range from 0.0 to 1.0. You want to multiply this by the range you want to create. double x = drand48() * 1000.0

+3
source

drand48 returns a number from the interval [0.0, 1.0) . Are you looking for a number from 1 to 1000? In this case, you need to multiply by 999 and add 1.

Actually, what do you expect?

+8
source

drand48() returns a double , while rand() returns int .

In addition, drand48() returns a value that is distributed between [0.0, 1.0) , so your formula should 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 can either scale the result of drand48() as described above, or use lrand48() with an existing formula.

+4
source

Source: https://habr.com/ru/post/1395190/


All Articles