[英]C++ Square Root Function Bug
我有一个c ++算法,可以计算整数的平方根。 除了一个缺陷外,该程序可以正常运行。 它无法计算低于1的数字的平方根。例如,它无法计算.5或.9或.0000001等的平方根,但在所有其他情况下按计划工作。 我有X设置所以它不允许负输入,但我仍然不明白为什么它不会返回任何小于1的值。
include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
double squareroot(double x)
{ /* computes the square root of x */
/* make sure x is not negative .. no math crimes allowed! */
assert(x >= 0);
if (x == 0) return 0;
/* the sqrt must be between xhi and xlo */
double xhi = x;
double xlo = 0;
double guess = x / 2;
/* We stop when guess*guess-x is very small */
while (abs(guess*guess - x) > 0.000001)
{
if (guess*guess > x) xhi = guess;
else xlo = guess;
guess = (xhi + xlo) / 2;
}
return guess;
}
/* Test Stub */
int main()
{
double testvalue;
cout << "\n Enter a TestValue= ";
cin >> testvalue;
cout << endl;
double testresult = squareroot(testvalue);
cout << "\n Square Root= " << testresult << "\n";
}
谢谢您的帮助! 我能够通过使用以下方法解决问题:
if (x<1) {
xhi = 1;
xlo = x;
guess = (x + 1) / 2;
}
0.5的平方根是~0.7。 如果检查失败,您的逻辑就是猜测一个较小的数字。 您需要做的是添加一个额外的检测层以查看数字是否<1,然后修改流量以增加下一个猜测而不是减少它。
在x <1的情况下,您需要更改初始边界,因为平方根不位于0和x之间,而是位于x和1之间
double xhi, xlo, guess;
if (x > 1){
xhi = x;
xlo = 0;
guess = x / 2;
}
else{
xhi = 1;
xlo = x;
guess = (x + 1) / 2;
}
添加一些调试输出。 这将有助于您理解为什么程序在x < 1.0
时永远不会收敛到解决方案。
while (abs(guess*guess - x) > 0.000001)
{
if (guess*guess > x)
{
cout << "Changing xhi\n";
xhi = guess;
}
else
{
cout << "Changing xlo\n";
xlo = guess;
}
guess = (xhi + xlo) / 2;
cout << "guess: " << guess << endl;
}
如果您遵循Newton-Raphson方法 ,程序将更快收敛。 此外,无论x
是否大于或小于1,它都可以工作。
double squareroot(double x)
{
/* make sure x is not negative .. no math crimes allowed! */
assert(x >= 0);
if (x == 0) return 0;
double guess = x / 2;
while (abs(guess*guess - x) > 0.000001)
{
double dx = 0.5*(guess*guess -x)/guess;
guess -= dx;
cout << "guess: " << guess << endl;
}
return guess;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.