Random Numbers in Nim

Here’s the translation of the Go code to Nim, along with explanations in Markdown format suitable for Hugo:

Nim’s random module provides pseudorandom number generation.

import std/random

proc main() =
  # For example, `rand(100)` returns a random int n,
  # 0 <= n < 100.
  echo rand(100), ",", rand(100)

  # `rand(1.0)` returns a float64 f,
  # 0.0 <= f < 1.0.
  echo rand(1.0)

  # This can be used to generate random floats in
  # other ranges, for example 5.0 <= f' < 10.0.
  echo (rand(1.0) * 5) + 5, ",", (rand(1.0) * 5) + 5

  # If you want a known seed, create a new
  # random number generator with a specific seed.
  var rng = initRand(42)
  echo rng.rand(100), ",", rng.rand(100)

  # Creating another RNG with the same seed will
  # produce the same sequence of numbers.
  var rng2 = initRand(42)
  echo rng2.rand(100), ",", rng2.rand(100)

main()

To run the program:

$ nim c -r random_numbers.nim
23,61
0.007884829918295145
7.158189186351896,9.340604127312485
75,40
75,40

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

Nim’s random module provides various functions for generating random numbers. The rand function is versatile and can be used with different types of arguments to generate integers or floating-point numbers in specific ranges.

For seeded random number generation, Nim uses a Mersenne Twister algorithm by default, which is different from Go’s PCG. However, the concept of seeded randomness remains the same.

See the Nim random module documentation for references on other random quantities that Nim can provide.