Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 134 ยท Text, Files and Time

Random and Math

Learn Kotlin random numbers and math - kotlin.random.Random with seeds, nextInt ranges, shuffled, random, kotlin.math functions, rounding, floating-point pitfalls, mod and hypot - with runnable examples.

Games roll dice, simulations sample from distributions, tests need sample data, shuffling a playlist needs a random order, and almost every program eventually needs a square root or a rounded price. Kotlin handles both topics in its standard library: kotlin.random.Random for randomness, and the package kotlin.math for mathematical functions, with no imports from Java necessary.

There is a catch with random numbers in a tutorial: by definition, you cannot predict their values. So the central idea of this lesson is the seed. A seeded generator produces the same "random" sequence every time, which makes programs reproducible, testable and, in our case, verifiable. After that we look at math functions, rounding, and the quirks of floating-point numbers that surprise everybody once.

Random numbers

Random.nextInt(until) returns an integer from 0 up to but excluding until. Random.nextInt(from, until) works with a range whose upper end is excluded, and Random.nextInt(range) accepts an IntRange (with an inclusive end). There are also nextDouble() (0.0 up to 1.0, excluded), nextBoolean(), nextLong(), nextBytes(n).

Without a seed, Random (the default object) gives different values on every run, and we cannot rely on exact output. So first, a program that prints only things that are true for any random run:

Kotlin Random without a seed: check ranges, not values

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 readln()), it gets the next line from this box.

Every line prints true regardless of the actual numbers, which is how you test random code: assert properties, not values. The mistake that costs most people an hour is the excluded upper bound: nextInt(1, 7) is the way to roll a six-sided die, because 7 is not included. The range form nextInt(1..6) includes both ends and often reads better; it is an extension function, so it needs import kotlin.random.nextInt.

Seeds: reproducible randomness

Random(seed) creates a generator that starts from a known state. Two generators with the same seed return exactly the same sequence, on every run and every machine. A random number generator is really a formula that turns the previous state into the next number, and the seed is the starting state.

Kotlin Seeded generators repeat themselves

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 readln()), it gets the next line from this box.

The sequence for seed 42 is the same today, tomorrow and on your friend's laptop. This is valuable in three situations: tests (a failing test with random input can be replayed), simulations and games (share a seed to share a world), and debugging (log the seed; if something goes wrong you can reproduce the exact run). In production code that needs unpredictability, the opposite holds: never seed with a constant.

kotlin.random.Random is not cryptographically secure. Never use it for passwords, session tokens, password-reset codes, or keys. Use java.security.SecureRandom for those; its output cannot be predicted from earlier values.

Picking, shuffling and sampling

Collections have random helpers: random() picks one element (and throws NoSuchElementException on an empty collection; randomOrNull() returns null instead), and shuffled() returns a shuffled copy. Both accept a Random argument, so you can pass a seeded one. shuffle() (without "d") shuffles a mutable list in place.

Kotlin random, shuffled and sampling 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 readln()), it gets the next line from this box.

shuffled() creates a new list and leaves the original alone, as the second print shows; the in-place shuffle() changes the list itself. The reliable way to pick distinct random elements is to shuffle once and take(n). Picking randomly in a loop and checking for duplicates works but wastes time as the pool shrinks. The weighted choice relies on an idea worth remembering: draw one number in the total weight range and walk through the weights until it falls into a slot. Here, 70 percent common, 25 rare, 5 epic, so the counts come out near 700, 250 and 50.

The kotlin.math package

Import functions from kotlin.math and you can use sqrt, pow, abs, min, max, sin, cos, ln and more as plain functions, plus the constants PI and E. Many also exist as extensions, like x.pow(2) and x.absoluteValue.

Kotlin Everyday 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 readln()), it gets the next line from this box.

Trigonometric functions use radians, not degrees: sin(PI / 2) is the sine of a right angle, 1.0. Floating-point math does not throw for impossible operations; it returns special values. Dividing a double by zero gives Infinity, 0.0 / 0 and sqrt(-1.0) give NaN ("not a number"). NaN is not even equal to itself, so test it with isNaN(). For integers, dividing by zero throws ArithmeticException instead.

Rounding

Four functions round doubles: floor (down), ceil (up), truncate (toward zero) and round (to nearest, with halves going to the nearest even number). Rounding to a number of decimals needs the trick of multiplying, rounding, dividing, or a formatter.

Kotlin floor, ceil, truncate, round

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 readln()), it gets the next line from this box.

round(2.5) is 2.0 and round(3.5) is 4.0: "banker's rounding" goes to the even neighbour, which avoids a statistical bias when rounding many values. The same holds for roundToInt(). If your business rule is "half rounds up", use BigDecimal with RoundingMode.HALF_UP. ceil is how you compute things like the number of boxes or pages needed: ceil(17 / 5.0) is 4 boxes.

For integer-only paging math, you can avoid floating point entirely: (items + perPage - 1) / perPage.

Integer division, remainder and mod

On integers, / truncates and % is the remainder, which has the sign of the dividend. That is surprising for negative numbers, and a bug source for things like wrapping around an array index. The function mod (and floorDiv) follow mathematical rules: the result of mod has the sign of the divisor.

Kotlin Remainder versus mod

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 readln()), it gets the next line from this box.

-7 % 3 is -1, but (-7).mod(3) is 2, and the latter is almost always what you want for wrapping indices, clock arithmetic and hashing. Also see the trap in the last two lines of arithmetic: 10 / 3 * 3.0 does integer division first (3), then multiplies, giving 9.0, while 10 / 3.0 * 3 gives 10.0.

Floating-point surprises

Double stores numbers in binary, and most decimal fractions (0.1, 0.2, 0.3) have no exact binary form. The tiny errors show up in comparisons and sums.

Kotlin 0.1 + 0.2 and how to compare doubles

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 readln()), it gets the next line from this box.

The first line prints 0.30000000000000004, the famous example, and the equality test is false. The remedy is to compare with a tolerance (nearlyEqual), never with ==. For money use whole cents in a Long or BigDecimal made from a string (BigDecimal("0.1")), not from a Double. Integers have their own trap: Int.MAX_VALUE + 1 wraps around to a huge negative number without any error. Use Math.addExact and friends (they throw ArithmeticException on overflow) or Long when values may grow large; see Working with Numbers.

Exceptions: invalid arguments

Random and math APIs check their arguments and throw standard exceptions. nextInt(5, 5) or nextInt(6, 1) ask for a range with no numbers in it; random() on an empty list has nothing to choose.

Kotlin Empty ranges and empty lists (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 readln()), it gets the next line from this box.

The first call is wrapped, so its failure is printed as the message bound must be greater than origin; the last one is not, so the program ends with java.util.NoSuchElementException: Collection is empty. Use randomOrNull() when emptiness is possible.

Putting it together: a small simulation

A seeded Random plus basic math can answer questions by simulation. How likely is it to get at least one six in four rolls of a die? The exact answer is 1 โˆ’ (5/6)^4, about 0.5177. Let us check by experiment.

Kotlin Estimating a probability by simulation

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 readln()), it gets the next line from this box.

With 100,000 trials the estimate is within a hundredth of the exact answer. More trials mean a better estimate, but the error shrinks slowly: ten times more trials only cut the error by about a factor of three. Because we used a fixed seed, anyone running this program gets the identical result.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call rolls a normal six-sided die (values 1 to 6)?

    The upper bound of nextInt(from, until) is excluded, so nextInt(1, 7) returns 1 to 6. The form nextInt(1..6) with a range also works.
  2. 2. What is the main benefit of Random(42) over Random.Default?

    A seed fixes the starting state of the generator, so the sequence is repeatable. It is not secure and can produce duplicates.
  3. 3. What is (-7).mod(3)?

    mod returns a result with the sign of the divisor, so it is in 0..2. The remainder operator -7 % 3 would give -1.
  4. 4. What does println(0.1 + 0.2 == 0.3) print, and why?

    The sum is 0.30000000000000004. Compare doubles with a tolerance, and use integers or BigDecimal for money.
  5. 5. Which should you use to generate a password-reset token?

    kotlin.random.Random is predictable, even when seeded with the time. SecureRandom is designed for security-sensitive values.

Summary

  • Random.nextInt(from, until) excludes until; nextInt(1..6) includes both ends. Test random code by asserting properties, never exact values.
  • Random(seed) makes the sequence reproducible; random(), shuffled() and shuffle() accept a Random. Use randomOrNull() for collections that may be empty. Shuffle then take(n) to pick distinct items.
  • Plain Random is not secure: use SecureRandom for tokens and keys.
  • kotlin.math offers sqrt, pow, abs, hypot, trig (in radians), logs and constants PI and E; invalid double math yields Infinity or NaN, not exceptions.
  • round goes to the even neighbour on halves; floor, ceil, truncate, roundToInt cover the rest; use mod (not %) to wrap values, and BigDecimal where decimals must be exact.
  • Doubles are approximate: compare with a tolerance and keep money in integers or BigDecimal.

Next: Bits and Bytes