[JavaScript] Complete Guide to Advanced Mathematical Calculations with Math Methods

目次

Overview

Numerical calculations in JavaScript are not limited to basic arithmetic. By utilizing the Math object, advanced operations necessary for scientific computing and statistical processing can be performed. This article explains how to use major mathematical functions such as absolute value, power, square root, and logarithms, as well as constants like Napier’s constant (the base of natural logarithms).

Specifications (Input/Output)

  • Input: Numerical values to be calculated.
  • Output: Calculation results from each mathematical function (Console log).

Basic Usage

Mathematical functions built into JavaScript are used directly in the form of Math.methodName() without the need for instantiation.

Major Mathematical Methods

MethodMeaningExample Result (x=16, y=2)
Math.abs(x)Absolute ValueConverts negative numbers to positive. Math.abs(-10) -> 10
Math.pow(x, y)Powerx raised to the power of y. Math.pow(2, 3) -> 8
Math.sign(x)Sign Judgment1 if positive, -1 if negative, 0 if zero.
Math.sqrt(x)Square RootSquare root of x. Math.sqrt(16) -> 4
Math.log(x)Natural LogarithmLogarithm with base e.
Math.exp(x)Exponential FunctionValue of e raised to the power of x.

Full Code (HTML / JavaScript)

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math Method Demo</title>
    <script src="advanced-math.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Check Calculation Results</h1>
        <p>Open the console (F12) to view the logs.</p>
    </div>
</body>
</html>

JavaScript (advanced-math.js)

/**
 * Demonstration of advanced mathematical calculations
 */
const performMathOperations = () => {
    console.log('--- 1. Absolute Value (Math.abs) ---');
    // Used when only the "magnitude" of a number is needed
    const posNum = 10;
    const negNum = -10;
    console.log(`abs(${posNum}): ${Math.abs(posNum)}`); // 10
    console.log(`abs(${negNum}): ${Math.abs(negNum)}`); // 10


    console.log('--- 2. Power (Math.pow) ---');
    // 2 to the power of 10 (1024)
    // Note: Can also be written as "2 ** 10" in ES2016+
    const base = 2;
    const exponent = 10;
    console.log(`${base} to the power of ${exponent}: ${Math.pow(base, exponent)}`);


    console.log('--- 3. Sign Judgment (Math.sign) ---');
    // Determines if a value is positive, negative, or zero
    // Returns: 1 (Pos), -1 (Neg), 0 (Zero), -0, NaN
    console.log(`sign(50): ${Math.sign(50)}`);   // 1
    console.log(`sign(-25): ${Math.sign(-25)}`); // -1
    console.log(`sign(0): ${Math.sign(0)}`);     // 0


    console.log('--- 4. Square Root (Math.sqrt) ---');
    // sqrt(16) = 4
    const area = 16;
    console.log(`sqrt(${area}): ${Math.sqrt(area)}`);


    console.log('--- 5. Natural Logarithm and Exponential (Math.log / Math.exp) ---');
    // Napier's constant e (approx. 2.718)
    console.log(`Napier's Constant (Math.E): ${Math.E}`);

    // log(e) is 1
    console.log(`log(e): ${Math.log(Math.E)}`); // 1

    // exp(1) is e^1 = e
    console.log(`exp(1): ${Math.exp(1)}`); // 2.718...
};

// Execute
performMathOperations();

Customization Points

  • Exponentiation Operator ()**: In modern JavaScript, it is standard to write a ** b instead of Math.pow(a, b). It is recommended to use this for higher readability.
  • Logarithms with Different Bases: Math.log(x) is the natural logarithm (base e). To use a common logarithm (base 10), use Math.log10(x), or Math.log2(x) for base 2.

Important Points

  • Square Root of Negative Numbers: Passing a negative number to Math.sqrt() results in NaN (Not a Number). Imaginary number calculations are not supported by standard functions.
  • Behavior of Math.sign: Math.sign returns a number (1, -1, 0), not a boolean. Exercise caution when using it in conditional branches.

Application: Finding the Distance Between Two Points (Euclidean Distance)the Pythagorean theorem in a coordinate planeの画像Getty Images

By combining Math.sqrt and Math.pow (or the ** operator), the distance between two points on a coordinate plane can be calculated using the following logic:

Formula: sqrt((x2 – x1)^2 + (y2 – y1)^2)

/**
 * Function to calculate the distance between two points
 */
const calculateDistance = (x1, y1, x2, y2) => {
    const diffX = x2 - x1;
    const diffY = y2 - y1;
    // Math.hypot(diffX, diffY) is also a simpler alternative
    return Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2));
};

console.log(`Distance: ${calculateDistance(0, 0, 3, 4)}`); // 5

Summary

By utilizing Math object methods, mathematical processing can be performed quickly and accurately without manually implementing complex formulas. Methods such as Math.abs and Math.sqrt are essential across various fields, including UI animation calculations and data analysis.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次