Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript generates random numbers


May 09, 2021 CoffeeScript


Table of contents


Create a random number

Problem

You need to generate random numbers in a certain range.

Solution

Use JavaScript's Math.random() to get floating-point numbers to satisfy 0-lt;X-lt;1.0. Use multiplication and Math.floor to get numbers in a certain range.

probability = Math.random()
0.0 <= probability < 1.0
# => true

# 注意百分位数不会达到 100。从 0100 的范围实际上是 101 的跨度。
percentile = Math.floor(Math.random() * 100)
0 <= percentile < 100
# => true

dice = Math.floor(Math.random() * 6) + 1
1 <= dice <= 6
# => true

max = 42
min = -13
range = Math.random() * (max - min) + min
-13 <= range < 42
# => true

Discuss

For JavaScript, it's more straightforward and faster.

It is important to note that JavaScript's Math.random() cannot generate random number seeds from the generator to get a specific value. Details can be referred to to to Produce predictable random numbers.

Produces a number from 0 to n (excluded), multiplied by n.
Produces a number from 1 to n (included), multiplied by n and then added 1.