Reputation: 3331
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.
Upvotes: 3
Views: 276
Reputation: 32878
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
Upvotes: 3