基础篇- iOS开发中常用的数学函数
2018-03-26 本文已影响6人
進无尽
在编程中我们总要进行一些数学运算以及数字处理,本文简单总结下常用的数学函数 。
常用函数
1、 三角函数
double sin (double);正弦
double cos (double);余弦
double tan (double);正切
2 、反三角函数
double asin (double); 结果介于[-PI/2, PI/2]
double acos (double); 结果介于[0, PI]
double atan (double); 反正切(主值), 结果介于[-PI/2, PI/2]
double atan2 (double, double); 反正切(整圆值), 结果介于[-PI, PI]
3 、双曲三角函数
double sinh (double);
double cosh (double);
double tanh (double);
4 、指数与对数
double exp (double);求取自然数e的幂
double sqrt (double);开平方
double log (double); 以e为底的对数
double log10 (double);以10为底的对数
double pow(double x, double y);计算以x为底数的y次幂
float powf(float x, float y); 功能与pow一致,只是输入与输出皆为浮点数
5 、取整
double ceil (double); 取上整
double floor (double); 取下整
6 、取整与取余
double modf (double, double*); 将参数的整数部分通过指针回传, 返回小数部分
double fmod (double, double); 返回两参数相除的余数
7 、绝对值
double fabs (double);求绝对值
double cabs(struct complex znum) ;求复数的绝对值
8 、标准化浮点数
double frexp (double f, int *p); 标准化浮点数, f = x * 2^p, 已知f求x, p ( x介于[0.5, 1] )
double ldexp (double x, int p); 与frexp相反, 已知x, p求f
9、四舍五入
extern float ceilf(float);
extern double ceil(double);
extern long double ceill(long double);
extern float floorf(float);
extern double floor(double);
extern long double floorl(longdouble);
extern float roundf(float);
extern double round(double);
extern long double roundl(longdouble);
ceil:如果参数是小数,则求最小的整数但不小于本身.
floor:如果参数是小数,则求最大的整数但不大于本身.
round:如果参数是小数,则求本身的四舍五入。
例如:如何值是3.4的话,则
3.4 -- round 3.000000
-- ceil 4.000000
-- floor 3.00000
10、随机数
srand((unsigned)time(0)); //不加这句每次产生的随机数不变
int i = rand() % 5;
srandom(time(0));
int i = random() % 5;
int i = arc4random() % 5 ;
注:rand()和random()实际并不是一个真正的伪随机数发生器,在使用之前需要先初始化随机种子,否则每次生成的随机数一样。
arc4random() 是一个真正的伪随机算法,不需要生成随机种子,
因为第一次调用的时候就会自动生成。而且范围是rand()的两倍。
在iPhone中,RAND_MAX是0x7fffffff (2147483647),而arc4random()返回的最大值则是 0x100000000 (4294967296)。
精确度比较:arc4random() > random() > rand()。
获取一个随机整数,范围在[from,to),包括from,不包括to
-(int)getRandomNumber:(int)from to:(int)to
{
return (int)(from + (arc4random() % (to – from + 1)));
//+1,result is [from to]; else is [from, to)!!!!!!!
}
11、其他
double hypot(double x, double y);已知直角三角形两个直角边长度,求斜边长度
double ldexp(double x, int exponent);计算x*(2的exponent次幂)
double poly(double x, int degree, double coeffs [] );计算多项式
常数
M_PI 圆周率(=π)
M_PI_2 圆周率的1/2(=π/2)
M_PI_4 圆周率的1/4(=π/4)
M_1_PI =1/π
M_2_PI =2/π
M_E =e
M_LOG2E log_2(e)
M_LOG10E log_10(e)