liveBook · Manning

Pseudo-random number generator

As explained in Clojure: The Essential Reference

A pseudorandom number generator is a deterministic algorithm that produces number sequences with statistical properties resembling random sequences.

A pseudo-random number generator produces useful random-looking values efficiently, while remaining algorithmic rather than perfectly random. Clojure exposes this capability through rand and rand-int, backed by Java generation facilities. section 5.10

Clojure's two functions differ in input and output:

  • rand with no arguments returns a double x where 0.0 ≤ x < 1.0; an optional bound must be a double. section 5.10
  • rand-int requires an integer bound and returns an integer from zero to that bound; negative bounds are allowed. section 5.10

A/B rollout

Use rand to select roughly half of requests for a feature: (if (< 0.5 (rand)) new-feature old-feature). For an integer choice, (rand-int -10) can produce a value such as -5. section 5.10

Listing 5.6. → Random Numbers Generation
(rand
  ([])
  ([n]))

(rand-int
  [n])

Browse the concise function signatures for rand and rand-int. section 5.10

How Clojure: The Essential Reference covers it

How deep it goes
Defines contracts, ranges, types, and outputs, then sketches linear congruential generation and repeating periods.
Examples
Demonstrates feature rollouts, sampled negative integers, random survey progress, image noise, and visible generator patterns.
What it assumes
Assumes basic Clojure function use and distinguishes ordinary randomness from stronger randomness requirements.
What you can do after
Apply rand and rand-int to generate bounded doubles or integers for practical randomized behavior.
How it connects
Connects Clojure functions with Java pseudo-random generation, linear congruential generators, and A/B testing.

Also explained in

Compare how 10 books explain pseudo-random number generator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.