Math.PI 是 JavaScript 內建的只讀屬性,表示圓周率 π(圓的周長與直徑之比)。其值為 3.141592653589793(IEEE 754 雙精度浮點數近似值)。
Math.PI
console.log(Math.PI); // 3.141592653589793
// 經典幾何計算
const radius = 5;
console.log('圓面積:', Math.PI * radius ** 2); // 78.5398...
console.log('圓周長:', 2 * Math.PI * radius); // 31.4159...
console.log('球體積:', (4/3) * Math.PI * radius ** 3); // 523.598...
console.log('球表面積:', 4 * Math.PI * radius ** 2); // 314.159...
JS 三角函數使用弧度,Math.PI 是轉換關鍵:
// 度 → 弧度
const degToRad = deg => deg * Math.PI / 180;
// 弧度 → 度
const radToDeg = rad => rad * 180 / Math.PI;
console.log(degToRad(180)); // 3.14159... (π)
console.log(radToDeg(Math.PI)); // 180
// 常用角度常量
const PI_2 = Math.PI / 2; // 90°
const PI_4 = Math.PI / 4; // 45°
const PI_6 = Math.PI / 6; // 30°
JS 原生 number 型別為 64 位浮點,約 15-17 位十進制精度。極高精度場景請使用:
function estimatePi(samples = 1000000) {
let inside = 0;
for (let i = 0; i < samples; i++) {
const x = Math.random();
const y = Math.random();
if (x * x + y * y <= 1) inside++;
}
return 4 * inside / samples;
}
console.log(estimatePi(1000000)); // 約 3.141xxx
| 常量 | 含義 | 近似值 |
|---|---|---|
Math.PI | π | 3.141592653589793 |
Math.SQRT2 | √2 | 1.4142135623730951 |
Math.SQRT1_2 | √(1/2) = 1/√2 | 0.7071067811865476 |
Math.E | e (自然對數底) | 2.718281828459045 |
Math.LN2 | ln(2) | 0.6931471805599453 |
Math.LN10 | ln(10) | 2.302585092994046 |
Math.PI 而非手寫 3.14 或 3.14159,保證最大精度Math.PI / 180,預先計算常量Math.PI 是幾何、三角、物理模擬、圖形學等領域的基石常量。善用它及相關轉換工具,能編寫出更精確、可維護的數學代碼。