我有f(x,num)=x*x-num
。它应该用#define
声明。我应该使用mysqrt来计算数字num
的平方根。主要是,我应该读一个num
到#34;出现 - 显示"变量num,mysqrt(num)和sqrt(num)。在函数mysqrt(num)中,我们在x
和oldx
上给出了首字母。 DO-而(| X-oldx |> 1E-15)。我们将x
内部保存到oldx
后。我们用方法x = x-f(x)/ f'(x)计算新的x。
我做错了什么?
#include <stdio.h>
#include <stdlib.h>
#define f(x) ((x) * (x) - (num))
#define fdx(x) (2 * (x))
double mysqrt(double num);
main() {
double num;
printf("the num is ", &num, &sqrt);
system("Pause");
} //end main
double mysqrt(double num) { //method
double x = 3; // i dont know if i did good i gave 3 a random number from my mind
double oldx = 1; // the same and here i did i gave a random number
double result;
double residual;
unsigned double iterations = 0;
result = sqrt(num);
x = num / 2; /* initial guess */
printf("sqrt(%g)=%.16g\n", num, result);
do {
printf("x%u=%.16g\n", iterations, x);
iterations++;
oldx = x;
// x=x-f(x)/f'(x)
x = x - f(x) / fdx(x);
residual = x - oldx;
} while (fabs(residual) > 1e-15);
printf("x%u=%.16g residual=%.16g\n", iterations, x, residual);
return x;
}
答案 0 :(得分:-1)
这称为牛顿计算sqrt的方法。你发现它随处可见。