Newbie1234567
Newbie1234567

Reputation: 41

Random numbers in Racket

I'm trying to generate random numbers from 0 to 1, including the borders 0 and 1 in Racket. Until now I didn't find a solution. Is there a nice way ?

Upvotes: 3

Views: 2037

Answers (2)

Alexis King
Alexis King

Reputation: 43902

As soegaard mentions in his answer, you should just use (random). It is true that it produces a number in the open range (0, 1), not the closed range [0, 1] that you want. However, I’m going to present an argument backed by some numbers that the difference is irrelevant.

The random procedure produces an IEEE 754 double-precision floating point number. The next-largest number representable by that format after 0 is approximately 4.94 × 10-324. If we assume that (random) does, indeed, produce a number uniformly distributed over the range, then that would imply that the probability of ever actually producing 0.0 is one in 4.94 × 10324! To give you a little bit of context for that number, that means that even if you generated one billion random numbers every second, it would still take on average 6.41 × 10306 years to generate 0.0 even once.

The situation is a little less grim at the other end of the range, since the difference between 1 and the next-smallest number representable by double flonums is significantly larger: approximately 1.11 × 10-16. On this end of the range, if we once again generated one billion random numbers every second, then it would take on average “only” 104 days before generating 1.0 for the first time. However, this would still be completely insignificant compared to the enormous amount of data you had already generated (and indeed, it’s rather unlikely you are going to be generating a billion random numbers per second to begin with, since it takes well over a minute just to generate a billion random numbers on my machine).

Don’t worry about those missing ends of the range, since they really won’t matter. Just call (random) and be done with it.

Upvotes: 9

soegaard
soegaard

Reputation: 31145

Use (random) to generate a number between 0.0 and 1.0.

To include 0.0 and 1.0 you can use:

(define (r)
  (/ (random 4294967087)
     4294967086.0))

Upvotes: 6

Related Questions