[JavaScript] Implementation Patterns for Advanced Mathematical Calculations with Math Methods

目次

Overview

In JavaScript numerical processing, the standard Math object is used for scientific calculations and statistical processing that basic arithmetic operations cannot handle. This article explains the specifications of major mathematical methods—such as absolute value, power, square root, and logarithmic functions—along with practical implementation examples.

Specifications (Input/Output)

  • Input: Numerical values to be calculated (positive, negative, or decimals).
  • Output: Calculation results of various mathematical functions (Console output).

Basic Usage

Methods of the Math object are called directly in the form of Math.methodName() without the need for instantiation.

Major Mathematical Methods

  • Math.abs(x): Absolute Value. Returns the numerical value with its sign removed. Example: Math.abs(-5) -> 5.
  • Math.pow(base, exp): Power. Returns the base raised to the power of exp. Example: Math.pow(2, 3) -> 8.
  • Math.sign(x): Sign Judgment. Returns 1 for positive, -1 for negative, and 0 for zero. Example: Math.sign(-10) -> -1.
  • Math.sqrt(x): Square Root. Returns the square root of x. Example: Math.sqrt(9) -> 3.
  • Math.log(x): Natural Logarithm. Returns the logarithm of x with base e (ln x). Example: Math.log(Math.E) -> 1.
  • Math.exp(x): Exponential Function. Returns the value of e raised to the power of x.

Note: Math.E is a constant representing Napier’s constant (the base of natural logarithms, approximately 2.718).


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 Operations Demo</title>
    <script src="math-calc.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Check Calculation Results</h1>
        <p>Press the F12 key to check the console logs.</p>
    </div>
</body>
</html>

JavaScript (math-calc.js)

/**
 * Demonstration of calculation processing using mathematical methods
 */
const runMathOperations = () => {
    console.log('--- 1. Absolute Value (Math.abs) ---');
    // Used to ignore signs when finding the deviation or distance between values
    const valA = 50;
    const valB = -50;
    console.log(`Input: ${valA} -> Result: ${Math.abs(valA)}`);
    console.log(`Input: ${valB} -> Result: ${Math.abs(valB)}`);


    console.log('--- 2. Power (Math.pow) ---');
    // 10 to the power of 3 (10 * 10 * 10)
    const base = 10;
    const exponent = 3;
    const powerResult = Math.pow(base, exponent);
    console.log(`${base} to the power of ${exponent}: ${powerResult}`);


    console.log('--- 3. Sign Judgment (Math.sign) ---');
    // Determines if a value is positive, negative, or zero
    // 1: Positive, -1: Negative, 0: Zero
    console.log(`sign(123): ${Math.sign(123)}`);
    console.log(`sign(-99): ${Math.sign(-99)}`);
    console.log(`sign(0): ${Math.sign(0)}`);


    console.log('--- 4. Square Root (Math.sqrt) ---');
    // Used for tasks like finding the length of a side from an area
    const areaSize = 25;
    console.log(`sqrt(${areaSize}) = ${Math.sqrt(areaSize)}`);


    console.log('--- 5. Logarithm and Exponential (Math.log, Math.exp) ---');
    // Base of natural logarithms e (Napier's constant)
    console.log(`Math.E (Constant): ${Math.E}`);
    
    // log(e) is 1
    console.log(`Math.log(Math.E): ${Math.log(Math.E)}`);
    
    // e squared (e^2)
    console.log(`Math.exp(2): ${Math.exp(2)}`);
};

// Execute the function
runMathOperations();

Customization Points

  • Using the Exponentiation Operator: Since ES2016, Math.pow(a, b) can be written using the ** operator (e.g., a ** b). This is recommended for better readability if your environment supports it.
  • Specifying the Base: Math.log(x) uses the natural logarithm (base e). If you need a common logarithm (base 10), use Math.log10(x); for base 2, use Math.log2(x).

Important Points

  • Square Root of Negative Numbers: Passing a negative value like Math.sqrt(-1) returns NaN (Not a Number). Standard JavaScript functionality does not support complex numbers.
  • Return Values for Sign Judgment: The return value of Math.sign() is a number (1, -1, 0, -0, NaN), not a boolean. When using it in conditional branches, you must compare it explicitly, such as === 1.

Application: Distance Calculation using the Pythagorean Theorem

By combining Math.sqrt and Math.pow, you can calculate the distance between two points on a coordinate plane.

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

// Distance between Point A(0, 0) and Point B(3, 4)
const x1 = 0, y1 = 0;
const x2 = 3, y2 = 4;

const distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));

console.log(`Distance between two points: ${distance}`); // 5

Summary

By utilizing the Math object, high-precision mathematical processing can be performed without implementing complex formulas manually. Methods like Math.abs (absolute value) and Math.sqrt (square root) are fundamental tools used across various fields, including UI animation control and data analysis. These methods ensure efficiency and accuracy in logic that requires mathematical rigor.

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

この記事を書いた人

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

目次