牛顿法求方程的解
#include <stdio.h>
#include <math.h>
#define F(x) ((x)*(x)*(x)-3*(x)*(x)+9*(x)-8)
#define G(x) (3*(x)*(x)-6*(x)+9)
int main(void) {
double x = 2;
// 出发点
double xn = 0;
// 第 n 回的近视值
double e = 0.000001;
// 解的精度
int n = 0;
// 回数
while (1) {
n++;
/* 计算牛顿迭代式 */
xn = x - F(x) / G(x);
printf("%d:x%d=(%.7lf),x%d=(%.7lf)\n", n, n, xn, n - 1, x);
if (fabs(xn - x) < e) {
break;
}
x = xn;
}
printf("在第 %d 回取到满足精度(%lf)的解:\n x = %.6lf\n", n, e, xn);
return 0;
}
牛顿法求平方根n次方根
#include <stdio.h>
#include <math.h>
// 牛顿法求平方根可拓展
double mySqrt(int x) {
double t=1.0; //初始迭代值
double cheak; //误差
double p = 1e-2; //误差上限
do
{
t = (x / t + t) / 2.0;
cheak = t * t - x;
} while((cheak >= 0 ? cheak : -cheak) > p);
return t;
}
double myCube(int x) {
double t=1.0;
double cheak;
double p = 1e-5;
do
{
t = (x / pow(t,2) + 2*t) / 3.0;
cheak = pow(t,3) - x;
} while((cheak >= 0 ? cheak : -cheak) > p);
return t;
}
// 牛顿法求n次方根可拓展
double nthRoot(int num,int n) {
double t=1.0;
double cheak;
double p = 1e-5;
do
{
t = (num / pow(t,(n-1)) + (n-1)*t) / n;
cheak = pow(t,n) - num;
} while((cheak >= 0 ? cheak : -cheak) > p);
return t;
}
int main () {
printf("mySqrt:2的平方根 = %f",mySqrt(2));
putchar(10);
printf("myCube:2的立方根 = %f",myCube(2));
putchar(10);
printf("nthRoot:2的平方根 = %f",nthRoot(2,2));
putchar(10);
printf("nthRoot:2的立方根 = %f",nthRoot(2,3));
return 0;
}