Math Operations and Utilities
Mathematical operations and utility functions
Challenge
Section titled “Challenge”Perform complex calculations, generate random numbers with correct distributions, and handle edge cases with special values.
Explanation
Section titled “Explanation”The Math object provides mathematical constants and functions. Understanding numeric precision and rounding is crucial for financial and scientific applications.
Basic Operations
Section titled “Basic Operations”// RoundingMath.round(4.5); // 5Math.round(4.4); // 4Math.floor(4.9); // 4Math.ceil(4.1); // 5Math.trunc(4.9); // 4
// Absolute valueMath.abs(-42); // 42
// Power and rootsMath.pow(2, 3); // 8Math.sqrt(16); // 4Math.cbrt(27); // 3
// Min and maxMath.min(1, 2, 3); // 1Math.max(1, 2, 3); // 3Math.min(...array); // Use spread operatorRandom Numbers
Section titled “Random Numbers”// Random decimal [0, 1)const random = Math.random();
// Random integer in rangefunction randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min;}console.log(randomInt(1, 10)); // 1-10
// Random element from arrayfunction randomElement(array) { return array[Math.floor(Math.random() * array.length)];}
// Shuffle array (Fisher-Yates)function shuffle(array) { const arr = [...array]; for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr;}Trigonometry
Section titled “Trigonometry”// Convert degrees to radiansfunction toRadians(degrees) { return degrees * (Math.PI / 180);}
// Trigonometric functionsconst angle = Math.PI / 4; // 45 degreesMath.sin(angle); // 0.707...Math.cos(angle); // 0.707...Math.tan(angle); // 1
// Inverse trigonometryMath.asin(0.707); // Angle in radiansMath.acos(0.707);Math.atan(1); // π/4
// Distance between pointsfunction distance(x1, y1, x2, y2) { return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));}Logarithms
Section titled “Logarithms”Math.log(Math.E); // 1 (natural log)Math.log10(100); // 2Math.log2(8); // 3Math.exp(1); // e^1
// Calculate order of magnitudefunction orderOfMagnitude(num) { return Math.floor(Math.log10(Math.abs(num)));}Numeric Edge Cases
Section titled “Numeric Edge Cases”// Special valuesconsole.log(Infinity); // Positive infinityconsole.log(-Infinity); // Negative infinityconsole.log(NaN); // Not a number
// Check for theseNumber.isFinite(100); // trueNumber.isFinite(Infinity); // falseNumber.isNaN(NaN); // trueisNaN('hello'); // true (uses type coercion)
// Floating point precision0.1 + 0.2; // 0.30000000000000004 (not 0.3!)
function floatEqual(a, b, epsilon = 1e-10) { return Math.abs(a - b) < epsilon;}console.log(floatEqual(0.1 + 0.2, 0.3)); // trueConstants
Section titled “Constants”Math.PI; // 3.14159...Math.E; // 2.71828... (Euler's number)Math.SQRT2; // √2Math.LN2; // Natural log of 2Math.LN10; // Natural log of 10