search
HomeWeb Front-endJS TutorialMastering JavaScript&#s Math Object: A Comprehensive Guide to Built-in Mathematical Functions and Properties

Mastering JavaScript

L'objet mathématique JavaScript : un aperçu

L'objet JavaScript Math est un objet intégré qui fournit une collection de fonctions et de constantes mathématiques. Ce n'est pas un constructeur, vous ne pouvez donc pas en créer des instances ; au lieu de cela, il est utilisé directement via ses méthodes et propriétés statiques.

1. Constantes

L'objet Math comprend plusieurs constantes utiles pour les calculs mathématiques :

  • Math.E : La base des logarithmes naturels, approximativement égale à 2,718.
  • Math.LN2 : Le logarithme népérien de 2, approximativement égal à 0,693.
  • Math.LN10 : Le logarithme népérien de 10, approximativement égal à 2,303.
  • Math.LOG2E : Le logarithme base 2 de E, approximativement égal à 1,442.
  • Math.LOG10E : Le logarithme base 10 de E, approximativement égal à 0,434.
  • Math.PI : Le rapport de la circonférence d'un cercle à son diamètre, approximativement égal à 3,14159.
  • Math.SQRT1_2 : La racine carrée de 1/2, approximativement égale à 0,707.
  • Math.SQRT2 : La racine carrée de 2, approximativement égale à 1,414.

2. Méthodes

L'objet Math propose plusieurs méthodes pour effectuer des opérations mathématiques :

  • Math.abs(x) : renvoie la valeur absolue de x.
  Math.abs(-5); // 5
  • Math.ceil(x) : Arrondit x à l'entier le plus proche.
  Math.ceil(4.2); // 5
  • Math.floor(x) : Arrondit x à l'entier le plus proche.
  Math.floor(4.7); // 4
  • Math.round(x) : Arrondit x à l'entier le plus proche.
  Math.round(4.5); // 5
  • Math.max(...values) : Renvoie le plus grand de zéro ou plusieurs nombres.
  Math.max(1, 5, 3); // 5
  • Math.min(...values) : Renvoie le plus petit de zéro ou plusieurs nombres.
  Math.min(1, 5, 3); // 1
  • Math.random() : renvoie un nombre pseudo-aléatoire compris entre 0 (inclus) et 1 (exclusif).
  Math.random(); // e.g., 0.237
  • Math.pow(base, exponent) : Renvoie la base élevée à la puissance exposant.
  Math.pow(2, 3); // 8
  • Math.sqrt(x) : Renvoie la racine carrée de x.
  Math.sqrt(9); // 3
  • Math.trunc(x) : renvoie la partie entière de x, en supprimant tous les chiffres fractionnaires.
  Math.trunc(4.9); // 4

3. Exemples d'utilisation

Voici quelques exemples pratiques de la façon dont vous pouvez utiliser l'objet Math :

  • Générer un entier aléatoire
  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  console.log(getRandomInt(1, 10)); // e.g., 7
  • Calcul de l'hypoténuse
  function calculateHypotenuse(a, b) {
    return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
  }
  console.log(calculateHypotenuse(3, 4)); // 5

4. Limites et remarques

  • Problèmes de précision : l'arithmétique à virgule flottante peut entraîner des problèmes de précision. Par exemple, Math.sqrt(2) * Math.sqrt(2) peut ne pas être exactement égal à 2 en raison d'erreurs d'arrondi.
  • Pas un constructeur : L'objet Math n'a pas de capacités de constructeur. Toutes les propriétés et méthodes sont statiques.

Méthodes et propriétés des objets mathématiques


1. Math.abs(x)

Renvoie la valeur absolue de x.

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

2. Math.acos(x)

Renvoie l'arccosinus (cosinus inverse) de x, en radians.

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

3. Math.acosh(x)

Renvoie l'arccosinus hyperbolique de x.

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

4. Math.asin(x)

Renvoie l'arc sinus (sinus inverse) de x, en radians.

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

5. Math.asinh(x)

Renvoie l'arc sinus hyperbolique de x.

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

6. Math.atan(x)

Renvoie l'arctangente (tangente inverse) de x, en radians.

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

7. Math.atan2(y, x)

Renvoie l'arctangente du quotient de ses arguments, en radians.

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

8. Math.atanh(x)

Renvoie l'arctangente hyperbolique de x.

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

9. Math.cbrt(x)

Renvoie la racine cubique de x.

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

10. Math.ceil(x)

Arrondit x vers le haut à l'entier le plus proche.

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

11. Math.clz32(x)

Renvoie le nombre de zéros non significatifs dans la représentation binaire 32 bits de x.

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

12. Math.cos(x)

Renvoie le cosinus de x (où x est en 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

The above is the detailed content of Mastering JavaScript&#s Math Object: A Comprehensive Guide to Built-in Mathematical Functions and Properties. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),