Getting a random real number in a certain range using WELL512

我们两清 提交于 2019-12-04 09:37:51
Nemo

Well, mathematically it's just:

min_value + (max_value - min_value) * (my_random() / (long double)ULONG_MAX)

(Assuming my_random() returns a uniformly distributed number between 0 and ULONG_MAX)

However, depending on the exact values of min_value, max_value, and ULONG_MAX, some floating point numbers will almost certainly be more likely than others.

Each possible random unsigned long maps to a float by this formula. But since the number of distinct floating point numbers between min_value and max_value is almost certainly not exactly ULONG_MAX, some unsigned longs will map to the same floating point number or some floating point numbers will have no unsigned long map to them or both.

Fixing this to make the result truly uniform is... non-trivial, I think. Maybe someone better read than I can cite a paper.

[edit]

Or see the answer to this question:

Generating random floating-point values based on random bit stream

That answer depends on the internals of the IEEE double representation. I am also not sure I fully understand how it works.

[edit 2]

OK now I understand how it works. The idea is to pick a random floating point representation between the min and the max, and then to throw it out with probability inversely proportional to its scale as represented by its exponent. Because for a uniform distribution, numbers between (say) 1/2 and 1 need to be half as likely as those between 1 and 2, but the number of floating point representations in those ranges is the same.

I think you could make that code more efficient by first picking the exponent on a logarithmic scale -- say, by using ffs on a randomly-chosen integer -- and then picking the mantissa at random. Hm...

Is it possible to convert the real number into unsigned long? If that is easily done, I think WELL512 works. Good luck.

It is quite simply impossible to represent uniformly distributed real numbers using floating point numbers - there are an uncountably infinite number of real numbers in your range, but only a finite number of floating point numbers.

What is worse, the finite number of reals within your range that are representable as floating point numbers may not even be evenly distributed, if your range crosses a floating point exponent boundary.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!