C语言中三角与反三角函数的表达
C语言中三角函数与反三角函数的总结与对比
一、三角函数(Trigonometric Functions)
- 功能
- 计算角度的三角函数值(输入为弧度)。
- 常用函数
函数 数学表示 描述 示例( x = π/4
)sin(x)
sin(x) 正弦 sin(M_PI/4) ≈ 0.707
cos(x)
cos(x) 余弦 cos(M_PI/4) ≈ 0.707
tan(x)
tan(x) 正切 tan(M_PI/4) ≈ 1.0
sinh(x)
sinh(x) 双曲正弦 sinh(1) ≈ 1.175
cosh(x)
cosh(x) 双曲余弦 cosh(1) ≈ 1.543
tanh(x)
tanh(x) 双曲正切 tanh(1) ≈ 0.761
- 关键点
- 输入单位转换
- 输入单位是弧度,若输入为角度需手动转换角度 → 弧度:
double degrees = 45.0; double radians = degrees * (M_PI / 180.0); // 45° → π/4弧度
- 输入单位是弧度,若输入为角度需手动转换角度 → 弧度:
- M_PI常量
- M_PI常量可能需要手动定义:
#ifndef M_PI #define M_PI 3.14159265358979323846 #endif
- M_PI常量可能需要手动定义:
- 输入单位转换
二、反三角函数(Inverse Trigonometric Functions)
- 功能
- 计算三角函数的反函数(输出为弧度)。
- 常用函数
-
函数 数学表示 描述 输入范围 输出范围(弧度) 示例 asin(x) $\sin^{-1}(x)$ 反正弦 $[-1,1]$ $[-\frac{\pi}{2},\frac{\pi}{2}]$ asin(0.5) ≈ 0.523(即30°) acos(x) $\cos^{-1}(x)$ 反余弦 $[-1,1]$ $[0,\pi]$ acos(0.5) ≈ 1.047(即60°) atan(x) $\tan^{-1}(x)$ 反正切 任意实数 $(-\frac{\pi}{2},\frac{\pi}{2})$ atan(1) ≈ 0.785(即45°) atan2(y, x) $\tan^{-1}(\frac{y}{x})$ 四象限反正切 任意实数 $(-\pi,\pi]$ atan2(1, 1) ≈ 0.785(即45°) - 关键点
- 输出单位转换
- 输出单位是弧度,需手动转换弧度 → 角度:
double radians = asin(0.5); double degrees = radians * (180.0 / M_PI); // 30°
- 输出单位是弧度,需手动转换弧度 → 角度:
- atan2的优势
- atan2(y, x)比atan(y/x)更稳定,可正确处理象限和x = 0的情况。
- 输出单位转换
三、对比总结
特性 | 三角函数(sin/cos/tan) | 反三角函数(asin/acos/atan) |
---|---|---|
输入 | 弧度(Radians) | 三角函数值(如$\sin^{-1}(0.5)$) |
输出 | 三角函数值(如$\sin(\frac{\pi}{2}) = 1$) | 弧度(Radians) |
常用场景 | 坐标旋转、波形生成 | 角度计算、极坐标转换 |
单位转换 | 角度 → 弧度:$rad = deg * (\frac{\pi}{180})$ | 弧度 → 角度:$deg = rad * (\frac{180}{\pi})$ |
特殊函数 | sinh/cosh/tanh(双曲函数) | atan2(y, x)(四象限反正切) |
四、完整代码示例
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
int main() {
// 示例1:计算sin(30°)和arcsin(0.5)
double deg = 30.0;
double rad = deg * (M_PI / 180.0);
printf("sin(30°) = %f\n", sin(rad)); // 输出0.5
printf("arcsin(0.5) = %f°\n", asin(0.5) * (180.0 / M_PI)); // 输出30°
// 示例2:四象限反正切atan2
double y = 1.0, x = -1.0;
double angle_rad = atan2(y, x);
double angle_deg = angle_rad * (180.0 / M_PI);
printf("atan2(1, -1) = %f°\n", angle_deg); // 输出135°(第二象限)
return 0;
}
五、注意事项
- 数学库链接
- 编译时需加 -lm(如gcc prog.c -lm)。
- 输入/输出范围
- asin/acos的输入必须在$[-1,1]$之间,否则返回NaN。
- atan2(y, x)可处理所有实数,包括x = 0的情况。
- 精度问题
- 浮点数计算可能存在微小误差(如sin(π)不精确为0)。
掌握这些函数后,可轻松实现几何计算、信号处理、图形学等领域的数学运算!