Packages@accelint/math
random
Generate random numbers and integers within specified bounds
random
Generate a random number within the given bounds.
Usage
import { random } from '@accelint/math';
const value = random(0, 10);
// value >= 0 && value <= 10Reference
function random(min: number, max: number): numberParameters
| Parameter | Type | Description |
|---|---|---|
min | number | The minimum value in the range (inclusive). |
max | number | The maximum value in the range (inclusive). |
Returns
Returns a random number between min and max (inclusive).
Throws
RangeError- Throws ifmin > max.
Examples
Example: Generating random decimal
import { random } from '@accelint/math';
const value = random(0, 1);
// A decimal between 0 and 1 (inclusive)Example: Negative range
import { random } from '@accelint/math';
const value = random(-10, -5);
// A decimal between -10 and -5 (inclusive)Example: Same min and max
import { random } from '@accelint/math';
const value = random(5, 5);
// Approximately 5Good to know: Both bounds are inclusive. The function adds
Number.EPSILONto ensure the maximum value can be generated.
randomInt
Generate a random integer within the given bounds.
Usage
import { randomInt } from '@accelint/math';
const value = randomInt(0, 10);
// An integer: 0, 1, 2, ..., 9, or 10Reference
function randomInt(min: number, max: number): numberParameters
| Parameter | Type | Description |
|---|---|---|
min | number | The minimum value in the range (inclusive). |
max | number | The maximum value in the range (inclusive). |
Returns
Returns a random integer between min and max (inclusive).
Throws
RangeError- Throws ifmin > max.
Examples
Example: Generating dice roll
import { randomInt } from '@accelint/math';
const roll = randomInt(1, 6);
// A whole number: 1, 2, 3, 4, 5, or 6Example: Floating point boundaries
import { randomInt } from '@accelint/math';
const value = randomInt(0.5, 10.5);
// Integer between Math.ceil(0.5) and Math.floor(10.5)
// Result: 1, 2, 3, ..., 9, or 10Example: Same min and max
import { randomInt } from '@accelint/math';
const value = randomInt(5, 5);
// Always returns 5Good to know: When given floating point boundaries, the function uses
Math.ceilonminandMath.flooronmaxto ensure integer results.
Related
- clamp - Clamps a number within specified bounds