Skip to content
Tutorials Center
My learning

Topics

Lesson 78 of 134 ยท Standard Library

Random Numbers and Math

Learn random numbers and math in Ruby - rand, seeded Random generators for repeatable results, shuffle and sample, the Math module, Integer.sqrt, SecureRandom, and when randomness is safe.

Random numbers show up in games, simulations, sampling, test data, load balancing and security tokens. Math shows up everywhere else. Ruby covers both in the core library: rand and the Random class for pseudo-random numbers, the Math module for roots, powers, logarithms and trigonometry, and the SecureRandom library for values that must be unguessable.

The most important idea in this lesson is that "random" numbers from a computer are usually pseudo-random: a formula produces a long sequence that looks random, starting from a number called the seed. If you know the seed, you can repeat the whole sequence. That sounds like a flaw, but it is a superpower for tests and debugging, and a hazard for passwords. You will see both sides here. For the number types themselves, see Numbers.

rand and the default generator

Ruby rand with no seed (only shape is predictable)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This example prints only things that are always true, because the actual numbers change on every run. That is the first lesson of testing random code: assert properties (the range, the type), not exact values. rand(10) returns 0 to 9, never 10, and rand(1..6) includes both ends. A zero argument, rand(0), or none at all gives a float between 0 and 1.

Repeatable randomness with seeds

Random.new(seed) creates your own generator. Two generators with the same seed produce exactly the same sequence.

Ruby Seeded Random generators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The numbers printed above are the same on every run and on every machine with the same Ruby version, which is why seeded generators are perfect for reproducing a bug ("it failed with seed 8812") and for deterministic tests. A seed of Random.new_seed (what Ruby picks when you give none) is a large random integer; print it in your test output so you can rerun a failing case.

The exact sequence for a given seed is stable for the Mersenne Twister algorithm that Ruby uses, but the Ruby documentation does not promise it forever across versions. Treat seeded numbers as repeatable for a given Ruby version, not as a file format.

shuffle, sample and random choices

Arrays have shuffle and sample, and both accept a random: generator, so a seeded generator makes them repeatable too (see Array Algorithms).

Ruby shuffle and sample with a seed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

sample with no argument returns one element; with a count it returns that many distinct positions. A common bug is calling Random.new(5) again inside a loop: each fresh generator restarts the sequence, so you get the same value over and over. Create the generator once and pass it around. The last line demonstrates exactly that mistake; all eight characters would be identical, which is why only the length is printed.

The Math module

Math is a module of functions (call them as Math.sqrt(16)) plus the constants Math::PI and Math::E. Everything returns a Float.

Ruby Math functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Angles are in radians, not degrees: multiply degrees by Math::PI / 180. Floats cannot store most decimals exactly, which is why Math.sin(Math::PI) prints a tiny number instead of 0.0. Compare floats with a tolerance, never with ==, and round only when displaying.

Hyperbolic functions, frexp, erf and gamma

Math also has the hyperbolic functions (sinh, cosh, tanh and their inverses asinh, acosh, atanh), two functions that take a float apart and put it back together (frexp, ldexp), and the error and gamma functions used in statistics.

Ruby More Math functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Math.ldexp(f, e) is the exact inverse of Math.frexp. The domain rules below apply here too: Math.acosh(0.5) and Math.atanh(2) raise Math::DomainError.

Domain errors

Ruby Square root of a negative number (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The real output is main.rb:1:in 'Math.sqrt': Numerical argument is out of domain - sqrt (Math::DomainError). Math::DomainError is raised for inputs outside a function's domain (negative square roots, Math.log(-1)). Rescue it, or check the input first. For complex answers, use Complex or Integer#** with a fractional exponent, which returns a Complex for negative bases.

Integer.sqrt and exact integer math

Math.sqrt returns a float, and floats lose precision above 2**53. For exact integer results, Integer.sqrt works on the integer itself and handles huge numbers:

Ruby Integer.sqrt, pow with modulus and gcd

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

pow(exponent, modulus) computes exponent powers modulo modulus without building the enormous intermediate number, which matters in cryptography and hashing. divmod returns quotient and remainder with the floor rule you learned in Numbers: -7.divmod(2) is [-4, 1], not [-3, -1].

SecureRandom: randomness you can trust

Random is fast and repeatable, which is exactly what you do not want for passwords, session tokens or API keys. If an attacker learns a few outputs, they can often reconstruct the generator state and predict the rest. For anything security-related use SecureRandom, which reads from the operating system's cryptographic source.

Ruby SecureRandom (only lengths and formats are printed)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

SecureRandom.hex(16) yields 32 characters because each byte becomes two hex digits. SecureRandom.uuid produces a version-4 UUID, a good identifier when you need a unique id without a database counter. You cannot seed SecureRandom, so you cannot reproduce its output: for tests, assert the format, as shown above.

Simulation example: estimating pi

A classic use of randomness is the Monte Carlo method. Throw random darts at a unit square; the fraction that lands inside the quarter circle approaches pi divided by four.

Ruby Monte Carlo estimate of pi with a seeded generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Because the generator is seeded and passed in as an argument, the run is identical every time and a test can check the result. Passing rng into the method (dependency injection) is the pattern to copy: a method that calls the global rand inside is hard to test.

When to use which

  • rand / Random.new(seed): games, simulations, shuffling, test data, anything where repeatability is welcome.
  • SecureRandom: tokens, passwords, keys, nonces and anything an attacker could benefit from guessing.
  • Math: float functions; Integer.sqrt, pow(e, m), gcd for exact integers.
  • Never use rand for security, never compare floats with ==, and never call Random.new(seed) inside a loop.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which values can rand(10) return?

    rand with an Integer argument n returns an Integer in 0...n, so the top value n is never returned.
  2. 2. Two generators are created with Random.new(42). What is true?

    A seed fully determines the pseudo-random sequence, so equal seeds give equal sequences. That is what makes seeded tests repeatable.
  3. 3. What should you use to generate a session token?

    SecureRandom draws from the operating system's cryptographic generator. Seeded or time-based Random values can be predicted.
  4. 4. Why does Math.sqrt(-4) not return a number?

    Ruby's Math functions raise Math::DomainError for arguments they cannot handle, instead of returning NaN.
  5. 5. What is the best way to test a method that uses randomness?

    Injecting a seeded generator makes the output repeatable, and property checks like a value lying in 1..6 hold for every run.

Summary

  • rand(n) gives an integer from 0 to n-1, rand(a..b) includes both ends, rand alone gives a float below 1.0.
  • Random.new(seed) makes repeatable sequences; pass the generator to shuffle(random:) and sample(random:) and to your own methods.
  • Create one generator and reuse it; a fresh Random.new(5) in a loop repeats the same number.
  • Math works in radians and floats, and raises Math::DomainError for invalid input; use Integer.sqrt, pow(e, m) and gcd for exact integer work.
  • Use SecureRandom for anything security-related, and test it by format, not by value.

Next: JSON