Random Number
 

Random Number

The output of the functions getRandomInt( min, max ) and getRandomFloat( min, max ) can be seen using Developer Tools Console by pressing F12.

The code

<script>
/**
* Generates a random integer between min and max (inclusive).
* @param {number} min - The minimum value (inclusive).
* @param {number} max - The maximum value (inclusive).
* @returns {number} Random integer between min and max.
*/
function getRandomInt(min, max) {
// Validate inputs
if (typeof min !== "number" || typeof max !== "number") {
throw new Error("Both min and max must be numbers.");
}
if (min > max) {
throw new Error("min cannot be greater than max.");
}
// Ensure integer bounds
min = Math.ceil(min);
max = Math.floor(max);

return Math.floor(Math.random() * (max - min + 1)) + min;
}

/** * Generates a random floating-point number between min and max (inclusive of min, exclusive of max). * @param {number} min - The minimum value. * @param {number} max - The maximum value. * @returns {number} Random float between min and max. */ function getRandomFloat(min, max) { if (typeof min !== "number" || typeof max !== "number") { throw new Error("Both min and max must be numbers."); } if (min >= max) { throw new Error("min must be less than max."); }
return Math.random() * (max - min) + min;
}
</script>

The code for this is relatively simple.

Top

Links

Link to PDF Disabled

If you require a copy please email tempusfugit.me.uk

Top

References -

  • 1 - JavaScript Random - https://www.w3schools.com/JS/js_random.asp
  • 2 - Math.random() - https:// developer.mozilla.org/en-US/docs/Web/ JavaScript/Reference/Global_Objects/Math/random
  • 3 - The Garden of earthly delights - https://en.wikipedia.org/wiki/The_Garden_of_Earthly_Delights#/media/File:The_Garden_of_earthly_delights.jpg