javascript

examples

examples.js
/**
 * 14.2 Math Object - Examples
 *
 * The Math object provides mathematical constants and functions.
 * It's not a constructor - all properties and methods are static.
 */

// ============================================
// 1. MATHEMATICAL CONSTANTS
// ============================================

console.log('=== Mathematical Constants ===');

console.log('Math.PI:', Math.PI); // 3.141592653589793
console.log('Math.E:', Math.E); // 2.718281828459045 (Euler's number)
console.log('Math.LN2:', Math.LN2); // 0.6931471805599453
console.log('Math.LN10:', Math.LN10); // 2.302585092994046
console.log('Math.LOG2E:', Math.LOG2E); // 1.4426950408889634
console.log('Math.LOG10E:', Math.LOG10E); // 0.4342944819032518
console.log('Math.SQRT2:', Math.SQRT2); // 1.4142135623730951
console.log('Math.SQRT1_2:', Math.SQRT1_2); // 0.7071067811865476

// ============================================
// 2. ROUNDING METHODS
// ============================================

console.log('\n=== Rounding Methods ===');

// Math.round() - rounds to nearest integer
console.log('--- Math.round() ---');
console.log('Math.round(2.4):', Math.round(2.4)); // 2
console.log('Math.round(2.5):', Math.round(2.5)); // 3
console.log('Math.round(2.6):', Math.round(2.6)); // 3
console.log('Math.round(-2.4):', Math.round(-2.4)); // -2
console.log('Math.round(-2.5):', Math.round(-2.5)); // -2 (toward +∞)
console.log('Math.round(-2.6):', Math.round(-2.6)); // -3

// Math.floor() - rounds down (toward -∞)
console.log('\n--- Math.floor() ---');
console.log('Math.floor(2.9):', Math.floor(2.9)); // 2
console.log('Math.floor(2.1):', Math.floor(2.1)); // 2
console.log('Math.floor(-2.1):', Math.floor(-2.1)); // -3 (toward -∞)
console.log('Math.floor(-2.9):', Math.floor(-2.9)); // -3

// Math.ceil() - rounds up (toward +∞)
console.log('\n--- Math.ceil() ---');
console.log('Math.ceil(2.1):', Math.ceil(2.1)); // 3
console.log('Math.ceil(2.9):', Math.ceil(2.9)); // 3
console.log('Math.ceil(-2.1):', Math.ceil(-2.1)); // -2 (toward +∞)
console.log('Math.ceil(-2.9):', Math.ceil(-2.9)); // -2

// Math.trunc() - removes decimal part
console.log('\n--- Math.trunc() ---');
console.log('Math.trunc(2.9):', Math.trunc(2.9)); // 2
console.log('Math.trunc(2.1):', Math.trunc(2.1)); // 2
console.log('Math.trunc(-2.9):', Math.trunc(-2.9)); // -2
console.log('Math.trunc(-2.1):', Math.trunc(-2.1)); // -2

// Rounding to decimal places
console.log('\n--- Rounding to Decimal Places ---');

function roundTo(num, decimals) {
  const factor = Math.pow(10, decimals);
  return Math.round(num * factor) / factor;
}

console.log('roundTo(3.14159, 2):', roundTo(3.14159, 2)); // 3.14
console.log('roundTo(3.14159, 4):', roundTo(3.14159, 4)); // 3.1416

function floorTo(num, decimals) {
  const factor = Math.pow(10, decimals);
  return Math.floor(num * factor) / factor;
}

console.log('floorTo(3.999, 2):', floorTo(3.999, 2)); // 3.99

function ceilTo(num, decimals) {
  const factor = Math.pow(10, decimals);
  return Math.ceil(num * factor) / factor;
}

console.log('ceilTo(3.001, 2):', ceilTo(3.001, 2)); // 3.01

// ============================================
// 3. MIN AND MAX
// ============================================

console.log('\n=== Min and Max ===');

// Basic usage
console.log('Math.min(1, 2, 3):', Math.min(1, 2, 3)); // 1
console.log('Math.max(1, 2, 3):', Math.max(1, 2, 3)); // 3

// With negative numbers
console.log('Math.min(-1, -5, 0):', Math.min(-1, -5, 0)); // -5
console.log('Math.max(-1, -5, 0):', Math.max(-1, -5, 0)); // 0

// With arrays (use spread operator)
const numbers = [5, 2, 8, 1, 9, 3];
console.log('\nArray:', numbers);
console.log('Math.min(...numbers):', Math.min(...numbers)); // 1
console.log('Math.max(...numbers):', Math.max(...numbers)); // 9

// Edge cases
console.log('\n--- Edge Cases ---');
console.log('Math.min():', Math.min()); // Infinity
console.log('Math.max():', Math.max()); // -Infinity
console.log('Math.min(1, NaN, 3):', Math.min(1, NaN, 3)); // NaN
console.log('Math.max(1, undefined, 3):', Math.max(1, undefined, 3)); // NaN

// ============================================
// 4. RANDOM NUMBERS
// ============================================

console.log('\n=== Random Numbers ===');

// Basic random (0 to 1, excluding 1)
console.log('Math.random():', Math.random());
console.log('Math.random():', Math.random());
console.log('Math.random():', Math.random());

// Random integer from 0 to max (exclusive)
function randomInt(max) {
  return Math.floor(Math.random() * max);
}
console.log('\nrandomInt(10):', randomInt(10)); // 0-9
console.log('randomInt(10):', randomInt(10));
console.log('randomInt(10):', randomInt(10));

// Random integer in range [min, max] (inclusive)
function randomRange(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log('\nrandomRange(1, 6) - dice roll:', randomRange(1, 6));
console.log('randomRange(1, 6) - dice roll:', randomRange(1, 6));
console.log('randomRange(1, 6) - dice roll:', randomRange(1, 6));

// Random float in range
function randomFloat(min, max) {
  return Math.random() * (max - min) + min;
}
console.log('\nrandomFloat(1.5, 3.5):', randomFloat(1.5, 3.5));

// Random boolean
function randomBool() {
  return Math.random() < 0.5;
}
console.log('\nrandomBool():', randomBool());
console.log('randomBool():', randomBool());

// Random array element
function randomElement(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}
const colors = ['red', 'green', 'blue', 'yellow'];
console.log('\nRandom color:', randomElement(colors));
console.log('Random color:', randomElement(colors));

// Shuffle array (Fisher-Yates algorithm)
function shuffle(arr) {
  const result = [...arr];
  for (let i = result.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [result[i], result[j]] = [result[j], result[i]];
  }
  return result;
}
console.log('\nOriginal:', [1, 2, 3, 4, 5]);
console.log('Shuffled:', shuffle([1, 2, 3, 4, 5]));

// ============================================
// 5. POWER AND ROOT METHODS
// ============================================

console.log('\n=== Power and Root Methods ===');

// Math.pow() and ** operator
console.log('--- Powers ---');
console.log('Math.pow(2, 3):', Math.pow(2, 3)); // 8
console.log('2 ** 3:', 2 ** 3); // 8 (ES2016)
console.log('Math.pow(2, 0.5):', Math.pow(2, 0.5)); // 1.414... (square root)
console.log('2 ** -1:', 2 ** -1); // 0.5
console.log('10 ** 6:', 10 ** 6); // 1000000

// Square root
console.log('\n--- Square Root ---');
console.log('Math.sqrt(16):', Math.sqrt(16)); // 4
console.log('Math.sqrt(2):', Math.sqrt(2)); // 1.414...
console.log('Math.sqrt(-1):', Math.sqrt(-1)); // NaN

// Cube root
console.log('\n--- Cube Root ---');
console.log('Math.cbrt(27):', Math.cbrt(27)); // 3
console.log('Math.cbrt(-8):', Math.cbrt(-8)); // -2
console.log('Math.cbrt(1000):', Math.cbrt(1000)); // 10

// Hypotenuse
console.log('\n--- Hypotenuse ---');
console.log('Math.hypot(3, 4):', Math.hypot(3, 4)); // 5 (3-4-5 triangle)
console.log('Math.hypot(5, 12):', Math.hypot(5, 12)); // 13
console.log('Math.hypot(1, 1):', Math.hypot(1, 1)); // 1.414... (√2)

// Distance between two points
function distance(x1, y1, x2, y2) {
  return Math.hypot(x2 - x1, y2 - y1);
}
console.log('\nDistance (0,0) to (3,4):', distance(0, 0, 3, 4)); // 5

// ============================================
// 6. ABSOLUTE VALUE AND SIGN
// ============================================

console.log('\n=== Absolute Value and Sign ===');

// Math.abs()
console.log('--- Math.abs() ---');
console.log('Math.abs(-5):', Math.abs(-5)); // 5
console.log('Math.abs(5):', Math.abs(5)); // 5
console.log('Math.abs(-3.14):', Math.abs(-3.14)); // 3.14
console.log('Math.abs(0):', Math.abs(0)); // 0

// Math.sign()
console.log('\n--- Math.sign() ---');
console.log('Math.sign(-5):', Math.sign(-5)); // -1
console.log('Math.sign(0):', Math.sign(0)); // 0
console.log('Math.sign(5):', Math.sign(5)); // 1
console.log('Math.sign(-0):', Math.sign(-0)); // -0

// ============================================
// 7. EXPONENTIAL AND LOGARITHMIC
// ============================================

console.log('\n=== Exponential and Logarithmic ===');

// Exponential functions
console.log('--- Exponential ---');
console.log('Math.exp(1):', Math.exp(1)); // 2.718... (e¹)
console.log('Math.exp(2):', Math.exp(2)); // 7.389... (e²)
console.log('Math.exp(0):', Math.exp(0)); // 1 (e⁰)
console.log('Math.expm1(0):', Math.expm1(0)); // 0 (e⁰ - 1)

// Natural logarithm (base e)
console.log('\n--- Natural Logarithm ---');
console.log('Math.log(Math.E):', Math.log(Math.E)); // 1
console.log('Math.log(1):', Math.log(1)); // 0
console.log('Math.log(10):', Math.log(10)); // 2.302...
console.log('Math.log(0):', Math.log(0)); // -Infinity
console.log('Math.log(-1):', Math.log(-1)); // NaN

// Base-2 and Base-10 logarithms
console.log('\n--- Other Logarithms ---');
console.log('Math.log2(8):', Math.log2(8)); // 3 (2³ = 8)
console.log('Math.log2(1024):', Math.log2(1024)); // 10
console.log('Math.log10(1000):', Math.log10(1000)); // 3 (10³ = 1000)
console.log('Math.log10(100):', Math.log10(100)); // 2

// Custom base logarithm
function logBase(x, base) {
  return Math.log(x) / Math.log(base);
}
console.log('\nlogBase(8, 2):', logBase(8, 2)); // 3
console.log('logBase(81, 3):', logBase(81, 3)); // 4 (3⁴ = 81)

// ============================================
// 8. TRIGONOMETRIC FUNCTIONS
// ============================================

console.log('\n=== Trigonometric Functions ===');

// Degree/Radian conversion
function toRadians(degrees) {
  return degrees * (Math.PI / 180);
}

function toDegrees(radians) {
  return radians * (180 / Math.PI);
}

console.log('--- Conversions ---');
console.log('90° in radians:', toRadians(90)); // 1.5707... (π/2)
console.log('π radians in degrees:', toDegrees(Math.PI)); // 180

// Sine
console.log('\n--- Sine ---');
console.log('Math.sin(0):', Math.sin(0)); // 0
console.log('Math.sin(π/2):', Math.sin(Math.PI / 2)); // 1
console.log('Math.sin(π):', Math.sin(Math.PI)); // ~0 (very small number)

// Cosine
console.log('\n--- Cosine ---');
console.log('Math.cos(0):', Math.cos(0)); // 1
console.log('Math.cos(π/2):', Math.cos(Math.PI / 2)); // ~0
console.log('Math.cos(π):', Math.cos(Math.PI)); // -1

// Tangent
console.log('\n--- Tangent ---');
console.log('Math.tan(0):', Math.tan(0)); // 0
console.log('Math.tan(π/4):', Math.tan(Math.PI / 4)); // 1 (tan 45°)

// Inverse trig functions
console.log('\n--- Inverse Trig ---');
console.log('Math.asin(1):', Math.asin(1)); // 1.5707... (π/2)
console.log('Math.acos(0):', Math.acos(0)); // 1.5707... (π/2)
console.log('Math.atan(1):', Math.atan(1)); // 0.7853... (π/4)

// atan2 - angle from origin to point (y, x)
console.log('\n--- atan2 ---');
console.log('Math.atan2(1, 1):', Math.atan2(1, 1)); // 0.7853... (45°)
console.log('Math.atan2(1, 0):', Math.atan2(1, 0)); // 1.5707... (90°)
console.log('Math.atan2(0, -1):', Math.atan2(0, -1)); // 3.1415... (180°)

// Angle between two points (in degrees)
function angle(x1, y1, x2, y2) {
  const radians = Math.atan2(y2 - y1, x2 - x1);
  return toDegrees(radians);
}
console.log('\nAngle from (0,0) to (1,1):', angle(0, 0, 1, 1)); // 45°

// ============================================
// 9. PRACTICAL EXAMPLES
// ============================================

console.log('\n=== Practical Examples ===');

// Circle calculations
function circleArea(radius) {
  return Math.PI * radius ** 2;
}

function circumference(radius) {
  return 2 * Math.PI * radius;
}

console.log('--- Circle (radius 5) ---');
console.log('Area:', circleArea(5)); // 78.539...
console.log('Circumference:', circumference(5)); // 31.415...

// Clamping values
function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}

console.log('\n--- Clamping ---');
console.log('clamp(150, 0, 100):', clamp(150, 0, 100)); // 100
console.log('clamp(-50, 0, 100):', clamp(-50, 0, 100)); // 0
console.log('clamp(50, 0, 100):', clamp(50, 0, 100)); // 50

// Linear interpolation
function lerp(start, end, t) {
  return start + (end - start) * t;
}

console.log('\n--- Linear Interpolation ---');
console.log('lerp(0, 100, 0):', lerp(0, 100, 0)); // 0
console.log('lerp(0, 100, 0.5):', lerp(0, 100, 0.5)); // 50
console.log('lerp(0, 100, 1):', lerp(0, 100, 1)); // 100

// Map range (scale value from one range to another)
function mapRange(value, inMin, inMax, outMin, outMax) {
  return ((value - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
}

console.log('\n--- Map Range ---');
console.log('mapRange(50, 0, 100, 0, 1):', mapRange(50, 0, 100, 0, 1)); // 0.5
console.log('mapRange(25, 0, 100, 0, 255):', mapRange(25, 0, 100, 0, 255)); // 63.75

// Percentage calculation
function percentage(part, whole) {
  return (part / whole) * 100;
}

console.log('\n--- Percentage ---');
console.log('75 out of 200:', percentage(75, 200) + '%'); // 37.5%

// Round to nearest multiple
function roundToNearest(num, multiple) {
  return Math.round(num / multiple) * multiple;
}

console.log('\n--- Round to Nearest Multiple ---');
console.log('roundToNearest(17, 5):', roundToNearest(17, 5)); // 15
console.log('roundToNearest(23, 5):', roundToNearest(23, 5)); // 25
console.log('roundToNearest(47, 10):', roundToNearest(47, 10)); // 50

// Factorial (iterative)
function factorial(n) {
  if (n < 0) return NaN;
  if (n === 0 || n === 1) return 1;
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}

console.log('\n--- Factorial ---');
console.log('factorial(5):', factorial(5)); // 120
console.log('factorial(10):', factorial(10)); // 3628800

// Check if power of 2
function isPowerOf2(n) {
  return n > 0 && Math.log2(n) % 1 === 0;
}

console.log('\n--- Power of 2 ---');
console.log('isPowerOf2(16):', isPowerOf2(16)); // true
console.log('isPowerOf2(15):', isPowerOf2(15)); // false
console.log('isPowerOf2(1024):', isPowerOf2(1024)); // true

console.log('\n=== Examples Complete ===');
Examples - JavaScript Tutorial | DeepML