Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to produce random double on POSIX?

I'd like to get uniform distribution in range [0.0, 1.0)

If possible, please let the implementation make use of random bytes from /dev/urandom.

It would also be nice if your solution was thread-safe. If you're not sure, please indicate that.

See some solution I thought about after reading other answers.

like image 200
Paweł Hajdan Avatar asked Mar 01 '23 07:03

Paweł Hajdan


1 Answers

This seems to be pretty good way:

unsigned short int r1, r2, r3;
// let r1, r2 and r3 hold random values
double result = ldexp(r1, -48) + ldexp(r2, -32) + ldexp(r3, -16);

This is based on NetBSD's drand48 implementation.

like image 158
Paweł Hajdan Avatar answered Mar 04 '23 03:03

Paweł Hajdan