Sling Academy
Home/JavaScript/Generating Gaussian-Like Random Numbers with Basic JavaScript Math

Generating Gaussian-Like Random Numbers with Basic JavaScript Math

Last updated: December 12, 2024

Generating random numbers that follow a Gaussian distribution, also known as a normal distribution, can be incredibly useful in various fields such as statistics, simulations, and data analysis. However, native JavaScript provides no direct way to generate Gaussian-distributed numbers. In this article, we'll explore how to achieve this using basic JavaScript math and additional code implementation.

Understanding Gaussian Distribution

Gaussian distribution is characterized by its bell-shaped curve and is defined by two parameters: the mean (μ) and the standard deviation (σ). The mean determines the center of the distribution, while the standard deviation controls the spread or width of the curve. In a lot of cases, random processes and measurements naturally follow a Gaussian distribution.

Box-Muller Transform

The Box-Muller Transform is a mathematical technique used to approximate and generate Gaussian-distributed random numbers from uniformly distributed random numbers.

Using Box-Muller Transform with JavaScript involves a few simple mathematical relationships. Let's walk through the creation of a function that generates Gaussian random numbers using the Box-Muller transform.

Code Implementation

function generateGaussianRandom(mean = 0, stddev = 1) {
    let u = 0, v = 0;
    while(u === 0) u = Math.random();
    while(v === 0) v = Math.random();
    let z = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
    return z * stddev + mean;
}

This generateGaussianRandom function will generate a Gaussian random variable with the specified mean and standard deviation. Here's a brief explanation of the code:

  • Math.random() generates a random number between 0 (inclusive) and 1 (exclusive).
  • Math.sqrt and Math.log transform these uniform random numbers according to the Box-Muller block.
  • Math.cos helps with the final part of the transformation to ensure the numbers follow the bell curve.
  • The resulting z is scaled and shifted by the stddev and mean respectively.

Testing Our Function

To validate the generated numbers follow a Gaussian distribution, we can generate a large number of samples and visualize them. For simplicity, we'll use the console for general checks.

let results = [];
let n = 10000; // Number of samples
let mean = 5;
let stddev = 2;

for(let i = 0; i < n; i++) {
    results.push(generateGaussianRandom(mean, stddev));
}

console.log('Sample mean:', results.reduce((sum, value) => sum + value, 0) / n);

For a proper visualization, consider using libraries like Chart.js or Plotly.js to plot the histogram of these samples, allowing you to visually confirm the bell-shaped curve characteristic of Gaussian distributions.

Conclusion

JavaScript, with a bit of mathematical insight, allows us to generate Gaussian random numbers useful for simulations and analysis. While native support does not exist, techniques such as the Box-Muller Transform and JavaScript's Math API offer a viable solution. Consider experimenting further by customizing the mean and standard deviation to suit specific needs.

Next Article: Applying Floor and Modulo Operations for Indexing in JavaScript

Previous Article: Exploring Math Constants (PI, E) for Geometric Formulas 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