Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (potentially) get all evenly distributed floating point values between 0 and 255

Assume integer below is produced by a true random number generator, and the number changes randomly between 0 and 255.

let integer = 241 // true random number

For the application I'm working on, I need to convert that number into a floating decimal between 0 and 1 to look more like the result from Math.random().

So,

let float = integer/((2**8)-1)

If integer changes to a new random integer between 0 and 255, will this provide other "quality" floating point numbers? For instance, would requesting Uint16 for numbers between 0–65535 then let float = integer/((2**16)-1) be a better approach just for the greater variety?

Note, my purposes for this is not for security, encryption, or cryptography. I just need the added decimal places similar to Math.random(). I am using these numbers to plug into a normalization transform using Box Müller to create a simulated random walk.

like image 972
Dshiz Avatar asked Dec 06 '25 18:12

Dshiz


1 Answers

In JavaScript, a Number is implemented as a binary floating-point number format with 53 significant bits of precision (more specifically, the binary64 format of IEEE 754).

However, generating a "uniform" floating-point number by multiplying or dividing an integer with a constant (as is commonly the case) will generally leave some floating-point numbers with no chance of occurring, even though they lie in the correct range and even though they can be represented in the floating-point format in question. For more information, see F. Goualard, "Generating Random Floating-Point Numbers by Dividing Integers: a Case Study".

Instead, a more complicated procedure can be done to give each floating-point number the expected probability of occurring (within the limits of the floating-point format), as I have done, for example. Note how non-trivial this procedure is. See also my answer to the question: Random floating point double in Inclusive Range

like image 53
Peter O. Avatar answered Dec 08 '25 07:12

Peter O.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!