Sling Academy
Home/JavaScript/Simulating Simple Randomized Experiments Using JavaScript Math

Simulating Simple Randomized Experiments Using JavaScript Math

Last updated: December 12, 2024

Simulating simple randomized experiments is a powerful way to understand the behavior of algorithms, probability, and various statistical outcomes. JavaScript, with its convenient Math library, offers several useful methods for such simulations. In this article, we'll explore how you can use JavaScript to perform simple randomized experiments, including generating random numbers, shuffling an array, and simulating coin flips and dice rolls.

Generating Random Numbers

The foundation of any randomized experiment is the generation of random numbers. JavaScript’s Math.random() method returns a floating-point pseudo-random number in the range from 0 (inclusive) up to but not including 1 (exclusive). You can scale this number to suit your needs.

// Generate a random number between 0 and 1
let randomNumber = Math.random();
console.log(randomNumber);

// Generate a random number between 0 and 100
let scaledRandomNumber = Math.random() * 100;
console.log(scaledRandomNumber);

// Generate a random integer between two values, min included, max excluded
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min);
}
console.log(getRandomInt(1, 10)); // random int between 1 and 9

Simulating Coin Flips

A simple example of using random numbers is simulating a coin flip. The coin can either land on heads or tails, each with a probability of 50%.

function coinFlip() {
  return Math.random() < 0.5 ? 'Heads' : 'Tails';
}

console.log(coinFlip()); // Outputs: Heads or Tails

The function uses Math.random() and checks if the result is less than 0.5. If true, it returns 'Heads'; otherwise, it returns 'Tails'.

Simulating Dice Rolls

Another common simulation is rolling a die, which involves generating a random number between 1 and 6. Here’s how you can simulate a dice roll in JavaScript:

function rollDice() {
  return Math.floor(Math.random() * 6) + 1;
}

console.log(rollDice()); // Outputs an integer between 1 and 6

This function multiplies the Math.random() result by 6 and applies Math.floor() to get a value between 0 and 5. Adding 1 shifts the range to between 1 and 6.

Randomly Shuffling an Array

Randomly shuffling items is another vital component of randomized experiments. You can create your own shuffling function using the Fisher-Yates (aka Knuth) Shuffle algorithm:

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

let numbers = [1, 2, 3, 4, 5];
console.log(shuffleArray(numbers)); // Outputs shuffled numbers array

This function iterates through the array from the last element to the first, swapping each element with another randomly chosen element that comes before it or itself, ensuring all possible permutations are equally likely.

Conclusion

Using the methods described above, you can perform a range of randomized experiments using JavaScript’s Math library. Whether you're simulating dice rolls, coin flips, or designing more complex experiments, understanding these basic techniques is essential for algorithm development, games, and probabilistic analysis. These simulations also serve as a robust educational aid in comprehending the laws of probability and randomness.

Previous Article: Improving Code Stability by Handling Numeric Special Cases in JavaScript

Series: JavaScript Numbers

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration