Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precision to drand48

Tags:

c++

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()?

like image 265
freshmaster Avatar asked Dec 04 '22 18:12

freshmaster


2 Answers

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?

like image 158
Roger Lipscombe Avatar answered Dec 07 '22 07:12

Roger Lipscombe


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.

like image 42
NPE Avatar answered Dec 07 '22 08:12

NPE