Random Numbers in F#

The System.Random class in F# provides pseudorandom number generation.

open System

let main() =
    let rand = Random()

    // For example, `Random.Next` returns a random int n,
    // 0 <= n < 100.
    printf "%d," (rand.Next(100))
    printfn "%d" (rand.Next(100))

    // `Random.NextDouble` returns a float64 f,
    // 0.0 <= f < 1.0.
    printfn "%f" (rand.NextDouble())

    // This can be used to generate random floats in
    // other ranges, for example 5.0 <= f' < 10.0.
    printf "%f," ((rand.NextDouble() * 5.0) + 5.0)
    printfn "%f" ((rand.NextDouble() * 5.0) + 5.0)

    // If you want a known seed, create a new
    // Random instance with a specific seed.
    let r2 = Random(42)
    printf "%d," (r2.Next(100))
    printfn "%d" (r2.Next(100))

    // Creating another Random instance with the same seed
    // will produce the same sequence of random numbers.
    let r3 = Random(42)
    printf "%d," (r3.Next(100))
    printfn "%d" (r3.Next(100))

main()

Some of the generated numbers may be different when you run the sample.

$ dotnet fsi random-numbers.fsx
68,56
0.809022813965918
5.840125017402497,6.937056298890035
94,49
94,49

See the Random Class documentation for references on other random quantities that F# can provide.