windows 在 C 中不使用来自 math.h 的 sqrt() 的预定义平方根函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/476966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Predefined squareroot function without using sqrt() from math.h in C
提问by gkrogers
Homework question:
家庭作业问题:
- Cygwin GNU GDB
- Cygwin GNU GCC
- Cygwin GNU GDB
- Cygwin GNU GCC
Attempting to establish the length of the hypotenuseC from the square root of Apower of 2 and Bpower of 2.
尝试根据A的 2次方和B的 2次方的平方根来确定斜边C的长度。
Exampleinput:
示例输入:
Enter the length of two sides of a right-angled triangle: 2.25 8.33
输入直角三角形两条边的长度:2.25 8.33
Answer:
回答:
The length of the hypotenuse is: 8.628523
斜边的长度为:8.628523
- Question:when I specify the same input as above, the result is not the same- output is 19.84.9596
- 问题:当我指定与上面相同的输入时,结果不一样——输出是19.84.9596
Full codebelow:
完整代码如下:
float squareRoots(float *s)
{
float cx;
float nx;
float e;
cx = 1;
nx = (cx +*s/cx)/2;
e = nx - cx;
cx = nx;
if (e*e > 0.001)
{
nx = (cx +*s/cx)/2;
return nx;
} else {
return nx;
}
}
float hypotenuse(float *a, float *b)
{
float c;
//raise a to power of 2
*a = (*a * *a);
*b = (*b * *b);
//add a and b
float y = *a + *b;
c = squareRoots(&y);
return c;
}
int main()
{
float x,y;
printf("Enter the length of two sides of a right-angled triangle:");
scanf("%f %f", &x, &y);
float k=hypotenuse(&x,&y);
printf("The length of the hypotenuse is: %f", k);
exit(0);
}
回答by Bill the Lizard
The square root algorithm you're (supposed to be?) using is called Newton's method. Your if statement should be a while loop.
您(应该是?)使用的平方根算法称为牛顿法。您的 if 语句应该是一个 while 循环。
Replace
代替
if (e*e > 0.001)
{
nx = (cx +*s/cx)/2;
return nx;
} else {
return nx;
}
with a while loop that iteratively does the same, but includes recalculating e.
使用while循环迭代执行相同的操作,但包括重新计算e。
I would give you the working code, but you said this is homework. If you can't get it to work, post your new code and I'll be happy to help you troubleshoot.
我会给你工作代码,但你说这是作业。如果您无法使用它,请发布您的新代码,我将很乐意帮助您进行故障排除。
回答by cletus
Want a super-duper square root implementation? Check out John Carmack's magic square root from Quake III.
想要一个超级骗子的平方根实现吗?从 Quake III 中查看John Carmack 的魔方根。
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 ****?
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;
}
回答by gkrogers
I make the answer 8.628522469, i.e. 8.628522.
我的答案是 8.628522469,即 8.628522。