# 开方的几种写法

+关注继续查看

1.牛顿迭代

……

    /**
* 牛顿迭代开平方
*/

public static double newtonInvertSqrt(double target) {
double point = 1;
double precision = 1e-2;
while (Math.abs(target - point * point) > precision) {
point = (point + target / point) / 2;

}

return point;

}

2.魔法数开方倒数

#include <math.h>
float InvSqrt(float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating VALUE
i = 0x5f375a86- (i>>1); // gives initial guess y0
x = *(float*)&i; // convert bits BACK to float
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
return x;
}

int main()
{
printf("%lf",1/InvSqrt(3));

return 0;
}  

float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;

x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

#ifndef Q3_VM
#ifdef __linux__
assert( !isnan(y) ); // bk010122 - FPE?
#endif
#endif
return y;
}

注意看代码
i = 0x5f3759df - ( i >> 1 ); // what the fuck?

……………… (1)

………………(2)

 i = 0x5f3759df - ( i >> 1 );  

public static double fastInvertSqrt(double number) {
long i;
double x2, y;
final double threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;

// evil floating point bit level hacking
i = Double.doubleToLongBits(y);

// gives initial guess y0
i = 0x5fe6eb50c7b537a9L - (i >> 1);

y = Double.longBitsToDouble(i);

// 1st iteration
y = y * (threehalfs - (x2 * y * y));

// 2nd iteration
y = y * (threehalfs - (x2 * y * y));

return 1 / y;
}

[1].果壳《求牛顿开方法的算法及其原理，此算法能开任意次方吗?

[2].维基百科《Fast inverse square root》https://en.wikipedia.org/wiki/Fast_inverse_square_root

[3].知乎《0x5f3759df这个快速开方中的常数的数学依据是什么？》https://www.zhihu.com/question/20690553

lodash两数相除
lodash两数相除
0 0
lodash两数相减
lodash两数相减
0 0

0 0

0 0
【初识C语言】简单计算n的阶乘以及多个数字的阶乘求和
【初识C语言】简单计算n的阶乘以及多个数字的阶乘求和
0 0

0 0

0 0
F#表达式化简

0 0

特点及意义 最大公约数指某几个整数共有因子中最大的一个。 GCD即Greatest Common Divisor. 例如，12和30的公约数有：1、2、3、6，其中6就是12和30的最大公约数。
785 0
+关注

nerd and proud