Math.cos(90) // 期望 0,實際返回 -0.4480736161291701
Math.sin(180) // 期望 0,實際返回 -1.2246467991473532e-16
JavaScript Math 對象所有三角函數參數均為弧度,而非角度。
90° = π/2 ≈ 1.5708 弧度Math.cos(1.5708) ≈ 6.123e-17 ≈ 0 (浮點數精度誤差)// 角度轉弧度
function degToRad(degrees) {
return degrees * Math.PI / 180;
}
// 弧度轉角度
function radToDeg(radians) {
return radians * 180 / Math.PI;
}
// 使用示例
console.log(Math.cos(degToRad(90))); // 6.123233995736766e-17 ≈ 0
console.log(Math.sin(degToRad(30))); // 0.5
console.log(Math.tan(degToRad(45))); // 0.9999999999999999 ≈ 1
const Trigonometry = {
// 基礎轉換
degToRad: deg => deg * Math.PI / 180,
radToDeg: rad => rad * 180 / Math.PI,
// 角度制三角函數
sin: deg => Math.sin(deg * Math.PI / 180),
cos: deg => Math.cos(deg * Math.PI / 180),
tan: deg => Math.tan(deg * Math.PI / 180),
// 反三角函數返回角度
asin: val => Math.asin(val) * 180 / Math.PI,
acos: val => Math.acos(val) * 180 / Math.PI,
atan: val => Math.atan(val) * 180 / Math.PI,
atan2: (y, x) => Math.atan2(y, x) * 180 / Math.PI,
// 雙精度修正 (解決 1e-16 顯示問題)
round: (val, precision = 10) =>
Math.round(val * Math.pow(10, precision)) / Math.pow(10, precision)
};
// 使用
console.log(Trigonometry.cos(90)); // 0
console.log(Trigonometry.round(Trigonometry.sin(30))); // 0.5
console.log(Trigonometry.atan2(1, 1)); // 45
| 表達式 | 理論值 | JS 計算值 | 修正後 |
|---|---|---|---|
Math.cos(Math.PI/2) | 0 | 6.123e-17 | Trigonometry.round(...) → 0 |
Math.sin(Math.PI) | 0 | 1.224e-16 | 0 |
Math.tan(Math.PI/4) | 1 | 0.9999999999999999 | 1 |
ctx.rotate(Trigonometry.degToRad(45)); // 旋轉 45 度
// 圓周運動
const x = centerX + radius * Trigonometry.cos(angle);
const y = centerY + radius * Trigonometry.sin(angle);
function getDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // 地球半徑 km
const dLat = Trigonometry.degToRad(lat2 - lat1);
const dLon = Trigonometry.degToRad(lon2 - lon1);
const a = Math.sin(dLat/2)**2 +
Math.cos(Trigonometry.degToRad(lat1)) *
Math.cos(Trigonometry.degToRad(lat2)) *
Math.sin(dLon/2)**2;
return 2 * R * Math.asin(Math.sqrt(a));
}
toFixed() 或自定義 round() 修正顯示