Generating Random Numbers in JS

Translation Notice
This article was machine-translated using DeepSeek-R1.

  • Original Version: Authored in Chinese by myself
  • Accuracy Advisory: Potential discrepancies may exist between translations
  • Precedence: The Chinese text shall prevail in case of ambiguity
  • Feedback: Technical suggestions regarding translation quality are welcomed
  • Generate random real numbers in $[0,1)$, i.e., $0\le\text{Math.random()} < 1$
1
2
3
4
5
Math.random()
// Example return values:
// #1: 0.60958701902852
// #2: 0.16182155144292465
// #3: 0.30126821448898133
  • Randomly generate integers in $[0, n]$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function randint1(n) { // Relatively balanced probability distribution
  return Math.round(Math.random() * n);
}

function randint2(n) { // n will never occur
  return Math.floor(Math.random() * n);
}

function randint3(n) { // Extremely low probability of 0, same as Math.random() producing 0
  return Math.ceil(Math.random() * n);
}
  • Generate random decimal numbers with one decimal place in $[0, n]$
1
2
3
4
// May have floating-point precision errors, e.g., 0.30000000000000004, 0.7999999999999999
function randf(n) {
  return Math.round(Math.random() * n * 10) / 10;
}
Built with Hugo
Theme Stack designed by Jimmy