The Math.random() method
The Math.random()
method returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). This method can be used for everything from simple randomization to complex simulations and games in Google Apps Script applications.
Prerequisites
This tutorial assumes that you're familiar with:
SyntaxMath.random()
Parameters
Math.random()
Not applicable - Math.random()
doesn't accept any parameters.
Return value
The Math.random()
function returns a floating-point number between 0 (inclusive) and 1 (exclusive), meaning it can be 0 but will never be 1.
ExamplesExample 1: Basic random number generation
In the code below, the function randomEx1()
demonstrates basic random number generation.
function randomEx1() {
// Basic random number between 0 and 1
Logger.log(Math.random()); // e.g., 0.7249841048464767
// Multiple calls produce different results
Logger.log(Math.random()); // e.g., 0.21638694561582367
Logger.log(Math.random()); // e.g., 0.5110456637524509
// Distribution test (approximate)
let counts = {
"0 to 0.25": 0,
"0.25 to 0.5": 0,
"0.5 to 0.75": 0,
"0.75 to 1": 0
};
for (let i = 0; i < 1000; i++) {
let r = Math.random();
if (r < 0.25) counts["0 to 0.25"]++;
else if (r < 0.5) counts["0.25 to 0.5"]++;
else if (r < 0.75) counts["0.5 to 0.75"]++;
else counts["0.75 to 1"]++;
}
Logger.log("Distribution of 1000 random numbers:");
Logger.log(counts); // Roughly 250 in each range
}
Output:
Note
The numbers generated when you run the above function will be different from the ones displayed below.
0.7249841048464767
0.21638694561582367
0.5110456637524509
Distribution of 1000 random numbers:
{0.75 to 1=240.0, 0.5 to 0.75=259.0, 0 to 0.25=247.0, 0.25 to 0.5=254.0}
Example 2: Generating random numbers in different ranges
In the code below, the function randomEx2()
shows how to generate random numbers within specific ranges.
function randomEx2() {
// Random integer between 1 and 10 (inclusive)
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Logger.log("Random integer between 1 and 10: " + getRandomInt(1, 10));
// Random integer between 0 and 99
Logger.log("Random integer between 0 and 99: " + Math.floor(Math.random() * 100));
// Random decimal between 0 and 10
Logger.log("Random decimal between 0 and 10: " + (Math.random() * 10));
// Random decimal between 5 and 15
Logger.log("Random decimal between 5 and 15: " + (5 + Math.random() * 10));
// Random boolean (true/false)
Logger.log("Random boolean: " + (Math.random() < 0.5));
}
Output:
Note
The numbers generated when you run the above function will be different from the ones displayed below.
Random integer between 1 and 10: 7
Random integer between 0 and 99: 42
Random decimal between 0 and 10: 6.123456789
Random decimal between 5 and 15: 11.987654321
Random boolean: false
Example 3: Applications in randomization
In the code below, the function randomEx3()
demonstrates common randomization techniques.
function randomEx3() {
// Randomly select item from an array
function getRandomItem(array) {
return array[Math.floor(Math.random() * array.length)];
}
let fruits = ["Apple", "Banana", "Orange", "Mango", "Kiwi"];
Logger.log("Random fruit: " + getRandomItem(fruits));
// Shuffle an array (Fisher-Yates algorithm)
function shuffleArray(array) {
let newArray = array.slice(); // Create a copy
for (let i = newArray.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
// Swap elements
[newArray[i], newArray[j]] = [newArray[j], newArray[i]];
}
return newArray;
}
Logger.log("Shuffled fruits: " + shuffleArray(fruits));
// Generate random hexadecimal color code
function getRandomColor() {
return "#" + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
}
Logger.log("Random color: " + getRandomColor());
}
Output:
Note
The values generated when you run the above function will be different from the ones displayed below.
Random fruit: Mango
Shuffled fruits: Kiwi,Orange,Apple,Mango,Banana
Random color: #a4e1c7
Example 4: Random data generation for Google Sheets
In the code below, the function randomEx4()
shows how to generate random data for a spreadsheet.
function randomEx4() {
// This function demonstrates creating random data for Google Sheets
// Generate a 2D array of random data
function generateRandomData(rows, cols) {
let data = [];
for (let i = 0; i < rows; i++) {
let row = [];
// Generate ID
let id = i + 1;
// Generate random name
let firstNames = ["John", "Jane", "Michael", "Sarah", "David", "Lisa"];
let lastNames = ["Smith", "Johnson", "Brown", "Wilson", "Davis", "Miller"];
let name = getRandomItem(firstNames) + " " + getRandomItem(lastNames);
// Generate random age (18-65)
let age = Math.floor(Math.random() * 48) + 18;
// Generate random salary ($30,000-$100,000)
let salary = Math.floor(30000 + Math.random() * 70000);
// Generate random performance score (1-5)
let score = Math.floor(Math.random() * 5) + 1;
row = [id, name, age, salary, score];
data.push(row);
}
return data;
function getRandomItem(array) {
return array[Math.floor(Math.random() * array.length)];
}
}
// Generate 5 rows of random employee data
let randomData = generateRandomData(5, 5);
// Log the generated data
Logger.log("Random employee data:");
for (let row of randomData) {
Logger.log(row.join(", "));
}
}
Note
In a real scenario, you would write this data to Google Sheets. The above function simulates this by logging the rows instead.
Output:
Note
The data generated when you run the above function will be different from that displayed below.
Random employee data:
1, John Smith, 45, 72348, 3
2, Lisa Brown, 32, 56789, 4
3, Michael Wilson, 51, 95432, 2
4, Sarah Davis, 27, 43210, 5
5, David Miller, 39, 67890, 1
Example 5: Monte Carlo simulation
In the code below, the function randomEx5()
demonstrates a simple Monte Carlo simulation to approximate the value of π
.
function randomEx5() {
// Monte Carlo method to estimate π
// If we place random points in a 2×2 square, the ratio of points inside a circle
// of radius 1 to total points will approximate π/4
function estimatePi(iterations) {
let insideCircle = 0;
for (let i = 0; i < iterations; i++) {
// Generate random coordinates between -1 and 1
let x = Math.random() * 2 - 1;
let y = Math.random() * 2 - 1;
// Check if point is inside the circle (x² + y² ≤ 1)
if (x*x + y*y <= 1) {
insideCircle++;
}
}
// Ratio approximates π/4
return (insideCircle / iterations) * 4;
}
Logger.log("Estimating π using Monte Carlo method:");
Logger.log("100 iterations: " + estimatePi(100));
Logger.log("1,000 iterations: " + estimatePi(1000));
Logger.log("10,000 iterations: " + estimatePi(10000));
Logger.log("100,000 iterations: " + estimatePi(100000));
Logger.log("Actual π: " + Math.PI);
}
Output:
Note
The numbers generated when you run the above function will be different from the ones displayed below.
Estimating π using Monte Carlo method:
100 iterations: 3.2
1,000 iterations: 3.192
10,000 iterations: 3.1484
100,000 iterations: 3.14192
1,000,000 iterations: 3.141288
Actual π: 3.141592653589793
Common Use Cases
The Math.random() function is useful in many scenarios when working with Google Apps Script:
Data sampling: Randomly selecting records from a dataset for analysis or testing.
Randomized testing: Creating test cases with random inputs to ensure robustness.
Simulations: Running Monte Carlo simulations for forecasting and risk analysis.
Games and quizzes: Creating randomized questions or game elements.
Educational tools: Generating random practice problems or examples.
UI elements: Adding random visual variations to charts, reports, or dashboards.
Data generation: Creating realistic test data for spreadsheets and forms.
Best Practices
When using the Math.random() function, keep these tips in mind:
Always remember that
Math.random()
returns a value between 0 (inclusive) and 1 (exclusive).For integer ranges, use
Math.floor(Math.random() * (max - min + 1)) + min
to ensure uniform distribution.Don't use
Math.random()
for security-critical applications or cryptographic purposes.For random integers, be careful about proper rounding and range boundaries to avoid bias.
Test randomization functions with large sample sizes to ensure they behave as expected.
Conclusion
In this tutorial, you learned how to use the Math.random()
method to generate random numbers in Google Apps Script. From basic random number generation to complex applications like Monte Carlo simulations, this function is a useful tool for many programming tasks.
DISCLAIMER: This content is provided for educational purposes only. All code, templates, and information should be thoroughly reviewed and tested before use. Use at your own risk. Full Terms of Service apply.
Small Scripts, Big Impact
Join 1,500+ professionals who are supercharging their productivity with Google Sheets automation
By subscribing, you agree to our Privacy Policy and Terms of Service