牛顿迭代公式
平方根迭代公式:a(n+1)=( a(n) + num/a(n) )/2,a(0) 初始化为1;
立方根迭代公式:a(n+1)=( 2a(n) + num/( (a(n))^2 ) )/3,a(0) 初始化为1;
程序计算过程
#include
#include
#define E 0.0001
using namespace std;
double getSqrtRoot(double num)
{
double x0=1, x1;
x1 = (x0 + num / x0) / 2.0;
while (fabs(x1 - x0) >= E)
{
x0 = x1;
x1 = (x0 + num / x0) / 2.0;
}
return x1;
}
double getCubeRoot(double num)
{
double x0, x1;
x0 = num;
x1 = (2 * x0 / 3) + (num / (3 * x0*x0));
while ((x1 - x0>E) || (x1 - x0<-E))
{
x0 = x1;
x1 = (2 * x0 / 3) + (num / (3 * x0*x0));
}
return x1;
}
int main()
{
double in;
while (cin >> in)
{
cout << fixed << showpoint << setprecision(1) << getCubeRoot(in) << endl;
cout << fixed << showpoint << setprecision(1) << getSqrtRoot(in) << endl;
}
return 0;
}