」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 掌握 JavaScript 的數學物件:內建數學函數和屬性的綜合指南

掌握 JavaScript 的數學物件:內建數學函數和屬性的綜合指南

發佈於2024-11-07
瀏覽:197

Mastering JavaScript

The JavaScript Math Object: An Overview

The JavaScript Math object is a built-in object that provides a collection of mathematical functions and constants. It is not a constructor, so you cannot create instances of it; instead, it is used directly through its static methods and properties.

1. Constants

The Math object includes several constants that are useful for mathematical calculations:

  • Math.E: The base of natural logarithms, approximately equal to 2.718.
  • Math.LN2: The natural logarithm of 2, approximately equal to 0.693.
  • Math.LN10: The natural logarithm of 10, approximately equal to 2.303.
  • Math.LOG2E: The base-2 logarithm of E, approximately equal to 1.442.
  • Math.LOG10E: The base-10 logarithm of E, approximately equal to 0.434.
  • Math.PI: The ratio of the circumference of a circle to its diameter, approximately equal to 3.14159.
  • Math.SQRT1_2: The square root of 1/2, approximately equal to 0.707.
  • Math.SQRT2: The square root of 2, approximately equal to 1.414.

2. Methods

The Math object provides several methods for performing mathematical operations:

  • Math.abs(x): Returns the absolute value of x.
  Math.abs(-5); // 5
  • Math.ceil(x): Rounds x up to the nearest integer.
  Math.ceil(4.2); // 5
  • Math.floor(x): Rounds x down to the nearest integer.
  Math.floor(4.7); // 4
  • Math.round(x): Rounds x to the nearest integer.
  Math.round(4.5); // 5
  • Math.max(...values): Returns the largest of zero or more numbers.
  Math.max(1, 5, 3); // 5
  • Math.min(...values): Returns the smallest of zero or more numbers.
  Math.min(1, 5, 3); // 1
  • Math.random(): Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).
  Math.random(); // e.g., 0.237
  • Math.pow(base, exponent): Returns the base raised to the exponent power.
  Math.pow(2, 3); // 8
  • Math.sqrt(x): Returns the square root of x.
  Math.sqrt(9); // 3
  • Math.trunc(x): Returns the integer part of x, removing any fractional digits.
  Math.trunc(4.9); // 4

3. Usage Examples

Here are a few practical examples of how you might use the Math object:

  • Generating a Random Integer
  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min   1))   min;
  }
  console.log(getRandomInt(1, 10)); // e.g., 7
  • Calculating the Hypotenuse
  function calculateHypotenuse(a, b) {
    return Math.sqrt(Math.pow(a, 2)   Math.pow(b, 2));
  }
  console.log(calculateHypotenuse(3, 4)); // 5

4. Limitations and Notes

  • Precision Issues: Floating-point arithmetic can lead to precision issues. For example, Math.sqrt(2) * Math.sqrt(2) might not exactly equal 2 due to rounding errors.
  • Not a Constructor: The Math object does not have constructor capabilities. All properties and methods are static.

Math Object Methods and Properties


1. Math.abs(x)

Returns the absolute value of x.

console.log(Math.abs(-10)); // 10
console.log(Math.abs(5.5)); // 5.5

2. Math.acos(x)

Returns the arccosine (inverse cosine) of x, in radians.

console.log(Math.acos(1)); // 0
console.log(Math.acos(0)); // 1.5707963267948966 (π/2)

3. Math.acosh(x)

Returns the hyperbolic arccosine of x.

console.log(Math.acosh(1)); // 0
console.log(Math.acosh(2)); // 1.3169578969248166

4. Math.asin(x)

Returns the arcsine (inverse sine) of x, in radians.

console.log(Math.asin(0)); // 0
console.log(Math.asin(1)); // 1.5707963267948966 (π/2)

5. Math.asinh(x)

Returns the hyperbolic arcsine of x.

console.log(Math.asinh(0)); // 0
console.log(Math.asinh(1)); // 0.881373587019543

6. Math.atan(x)

Returns the arctangent (inverse tangent) of x, in radians.

console.log(Math.atan(1)); // 0.7853981633974483 (π/4)
console.log(Math.atan(0)); // 0

7. Math.atan2(y, x)

Returns the arctangent of the quotient of its arguments, in radians.

console.log(Math.atan2(1, 1)); // 0.7853981633974483 (π/4)
console.log(Math.atan2(-1, -1)); // -2.356194490192345 (-3π/4)

8. Math.atanh(x)

Returns the hyperbolic arctangent of x.

console.log(Math.atanh(0)); // 0
console.log(Math.atanh(0.5)); // 0.5493061443340549

9. Math.cbrt(x)

Returns the cubic root of x.

console.log(Math.cbrt(27)); // 3
console.log(Math.cbrt(-8)); // -2

10. Math.ceil(x)

Rounds x upwards to the nearest integer.

console.log(Math.ceil(4.2)); // 5
console.log(Math.ceil(-4.7)); // -4

11. Math.clz32(x)

Returns the number of leading zeros in the 32-bit binary representation of x.

console.log(Math.clz32(1)); // 31
console.log(Math.clz32(0x80000000)); // 0

12. Math.cos(x)

Returns the cosine of x (where x is in radians).

console.log(Math.cos(0)); // 1
console.log(Math.cos(Math.PI)); // -1

13. Math.cosh(x)

Returns the hyperbolic cosine of x.

console.log(Math.cosh(0)); // 1
console.log(Math.cosh(1)); // 1.5430806348152437

14. Math.E

Returns Euler's number, approximately 2.718.

console.log(Math.E); // 2.718281828459045

15. Math.exp(x)

Returns the value of e raised to the power of x.

console.log(Math.exp(1)); // 2.718281828459045
console.log(Math.exp(0)); // 1

16. Math.expm1(x)

Returns the value of e raised to the power of x, minus 1.

console.log(Math.expm1(1)); // 1.718281828459045
console.log(Math.expm1(0)); // 0

17. Math.floor(x)

Rounds x downwards to the nearest integer.

console.log(Math.floor(4.7)); // 4
console.log(Math.floor(-4.2)); // -5

18. Math.fround(x)

Returns the nearest (32-bit single precision) float representation of x.

console.log(Math.fround(1.337)); // 1.336914
console.log(Math.fround(1.5)); // 1.5

19. Math.LN2

Returns the natural logarithm of 2, approximately 0.693.

console.log(Math.LN2); // 0.6931471805599453

20. Math.LN10

Returns the natural logarithm of 10, approximately 2.302.

console.log(Math.LN10); // 2.302585092994046

21. Math.log(x)

Returns the natural logarithm (base e) of x.

console.log(Math.log(Math.E)); // 1
console.log(Math.log(10)); // 2.302585092994046

22. Math.log10(x)

Returns the base-10 logarithm of x.

console.log(Math.log10(10)); // 1
console.log(Math.log10(100)); // 2

23. Math.LOG10E

Returns the base-10 logarithm of e, approximately 0.434.

console.log(Math.LOG10E); // 0.4342944819032518

24. Math.log1p(x)

Returns the natural logarithm of 1 x.

console.log(Math.log1p(1)); // 0.6931471805599453
console.log(Math.log1p(0)); // 0

25. Math.log2(x)

Returns the base-2 logarithm of x.

console.log(Math.log2(2)); // 1
console.log(Math.log2(8)); // 3

26. Math.LOG2E

Returns the base-2 logarithm of e, approximately 1.442.

console.log(Math.LOG2E); // 1.4426950408889634

27. Math.max(...values)

Returns the largest of zero or more numbers.

console.log(Math.max(1, 5, 3)); // 5
console.log(Math.max(-1, -5, -3)); // -1

28. Math.min(...values)

Returns the smallest of zero or more numbers.

console.log(Math.min(1, 5, 3)); // 1
console.log(Math.min(-1, -5, -3)); // -5

29. Math.PI

Returns the value of π, approximately 3.14159.

console.log(Math.PI); // 3.141592653589793

30. Math.pow(base, exponent)

Returns the value of base raised to the power of exponent.

console.log(Math.pow(2, 3)); // 8
console.log(Math.pow(5, 0)); // 1

31. Math.random()

Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).

console.log(Math.random()); // e.g., 0.237

32. Math.round(x)

Rounds x to the nearest integer.

console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4

33. Math.sign(x)

Returns the sign of a number, indicating whether the number is positive, negative, or zero.

console.log(Math.sign(-5)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(5)); // 1

34. Math.sin(x)

Returns the sine of x (where x is in radians).

console.log(Math.sin(0)); // 0
console.log(Math.sin(Math.PI / 2)); // 1

35. Math.sinh(x)

Returns the hyperbolic sine of x.

console.log(Math.sinh(0)); // 0
console.log(Math.sinh(1)); // 1.1752011936438014

36. Math.sqrt(x)

Returns the square root of x.

console.log(Math.sqrt(9)); // 3
console.log(Math.sqrt(16));

 // 4

37. Math.SQRT1_2

Returns the square root of 1/2, approximately 0.707.

console.log(Math.SQRT1_2); // 0.7071067811865476

38. Math.SQRT2

Returns the square root of 2, approximately 1.414.

console.log(Math.SQRT2); // 1.4142135623730951

39. Math.tan(x)

Returns the tangent of x (where x is in radians).

console.log(Math.tan(0)); // 0
console.log(Math.tan(Math.PI / 4)); // 1

40. Math.tanh(x)

Returns the hyperbolic tangent of x.

console.log(Math.tanh(0)); // 0
console.log(Math.tanh(1)); // 0.7615941559557649

41. Math.trunc(x)

Returns the integer part of a number by removing any fractional digits.

console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4
版本聲明 本文轉載於:https://dev.to/engrsakib/mastering-javascripts-math-object-a-comprehensive-guide-to-built-in-mathematical-functions-and-properties-1c2i?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何處理PHP文件系統功能中的UTF-8文件名?
    如何處理PHP文件系統功能中的UTF-8文件名?
    在PHP的Filesystem functions中處理UTF-8 FileNames 在使用PHP的MKDIR函數中含有UTF-8字符的文件很多flusf-8字符時,您可能會在Windows Explorer中遇到comploreer grounder grounder grounder gro...
    程式設計 發佈於2025-07-20
  • 如何從Google API中檢索最新的jQuery庫?
    如何從Google API中檢索最新的jQuery庫?
    從Google APIS 問題中提供的jQuery URL是版本1.2.6。對於檢索最新版本,以前有一種使用特定版本編號的替代方法,它是使用以下語法:獲取最新版本:未壓縮)While these legacy URLs still remain in use, it is recommended ...
    程式設計 發佈於2025-07-20
  • C++成員函數指針正確傳遞方法
    C++成員函數指針正確傳遞方法
    如何將成員函數置於c [&& && && && && && && && && && &&&&&&&&&&&&&&&&&&&&&&&華儀的函數時,在接受成員函數指針的函數時,要在函數上既要提供指針又可以提供指針和指針到函數的函數。需要具有一定簽名的功能指針。要通過成員函數,您需要同時提供對象指針(此...
    程式設計 發佈於2025-07-20
  • Python元類工作原理及類創建與定制
    Python元類工作原理及類創建與定制
    python中的metaclasses是什麼? Metaclasses負責在Python中創建類對象。就像類創建實例一樣,元類也創建類。他們提供了對類創建過程的控制層,允許自定義類行為和屬性。 在Python中理解類作為對象的概念,類是描述用於創建新實例或對象的藍圖的對象。這意味著類本身是使用...
    程式設計 發佈於2025-07-20
  • Spark DataFrame添加常量列的妙招
    Spark DataFrame添加常量列的妙招
    在Spark Dataframe ,將常數列添加到Spark DataFrame,該列具有適用於所有行的任意值的Spark DataFrame,可以通過多種方式實現。使用文字值(SPARK 1.3)在嘗試提供直接值時,用於此問題時,旨在為此目的的column方法可能會導致錯誤。 df.withCo...
    程式設計 發佈於2025-07-20
  • 如何在Chrome中居中選擇框文本?
    如何在Chrome中居中選擇框文本?
    選擇框的文本對齊:局部chrome-inly-ly-ly-lyly solument 您可能希望將文本中心集中在選擇框中,以獲取優化的原因或提高可訪問性。但是,在CSS中的選擇元素中手動添加一個文本 - 對屬性可能無法正常工作。 初始嘗試 state)</option> < o...
    程式設計 發佈於2025-07-20
  • Python高效去除文本中HTML標籤方法
    Python高效去除文本中HTML標籤方法
    在Python中剝離HTML標籤,以獲取原始的文本表示Achieving Text-Only Extraction with Python's MLStripperTo streamline the stripping process, the Python standard librar...
    程式設計 發佈於2025-07-20
  • 為什麼我在Silverlight Linq查詢中獲得“無法找到查詢模式的實現”錯誤?
    為什麼我在Silverlight Linq查詢中獲得“無法找到查詢模式的實現”錯誤?
    查詢模式實現缺失:解決“無法找到”錯誤在Silverlight應用程序中,嘗試使用LINQ建立LINQ連接以錯誤而實現的數據庫”,無法找到查詢模式的實現。”當省略LINQ名稱空間或查詢類型缺少IEnumerable 實現時,通常會發生此錯誤。 解決問題來驗證該類型的質量是至關重要的。在此特定實例...
    程式設計 發佈於2025-07-20
  • Java中Lambda表達式為何需要“final”或“有效final”變量?
    Java中Lambda表達式為何需要“final”或“有效final”變量?
    Lambda Expressions Require "Final" or "Effectively Final" VariablesThe error message "Variable used in lambda expression shou...
    程式設計 發佈於2025-07-20
  • C++20 Consteval函數中模板參數能否依賴於函數參數?
    C++20 Consteval函數中模板參數能否依賴於函數參數?
    [ consteval函數和模板參數依賴於函數參數在C 17中,模板參數不能依賴一個函數參數,因為編譯器仍然需要對非contexexpr futcoriations contim at contexpr function進行評估。 compile time。 C 20引入恆定函數,必須在編譯時進...
    程式設計 發佈於2025-07-20
  • Java的Map.Entry和SimpleEntry如何簡化鍵值對管理?
    Java的Map.Entry和SimpleEntry如何簡化鍵值對管理?
    A Comprehensive Collection for Value Pairs: Introducing Java's Map.Entry and SimpleEntryIn Java, when defining a collection where each element com...
    程式設計 發佈於2025-07-20
  • 如何將來自三個MySQL表的數據組合到新表中?
    如何將來自三個MySQL表的數據組合到新表中?
    mysql:從三個表和列的新表創建新表 答案:為了實現這一目標,您可以利用一個3-way Join。 選擇p。 *,d.content作為年齡 來自人為p的人 加入d.person_id = p.id上的d的詳細信息 加入T.Id = d.detail_id的分類法 其中t.taxonomy ...
    程式設計 發佈於2025-07-20
  • Go web應用何時關閉數據庫連接?
    Go web應用何時關閉數據庫連接?
    在GO Web Applications中管理數據庫連接很少,考慮以下簡化的web應用程序代碼:出現的問題:何時應在DB連接上調用Close()方法? ,該特定方案將自動關閉程序時,該程序將在EXITS EXITS EXITS出現時自動關閉。但是,其他考慮因素可能保證手動處理。 選項1:隱式關閉終...
    程式設計 發佈於2025-07-20
  • Java字符串非空且非null的有效檢查方法
    Java字符串非空且非null的有效檢查方法
    檢查字符串是否不是null而不是空的if (str != null && !str.isEmpty())Option 2: str.length() == 0For Java versions prior to 1.6, str.length() == 0 can be二手: if(str!= n...
    程式設計 發佈於2025-07-20

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3