首先,我想告诉你,英语不是我的自然语言所以也许是一个词或意义我不能表达正确。现在问题是我最近做了一个练习,问题是使用Newton-Raphson方法对于sqrt.Anyway,我认为这(sqrt)我做了它我不确定它。我不能做衍生物。而且,我认为我的代码有一些错误,如果你能解决它我会很好。方程是
x=sqrt(num)=>x*x=num=>f(x,num)=x*x-num=0
#include<stdio.h>
#include<stdlib.h>
#include <math.h> /* i use it for pow */
#definde f(x) ((x*x-num)/2x) /* this is the equation */
main(){
double num=8; /* i put what ever i want so i put 8 */
double result;
double oldx=2; /* i put what ever i want so i chose to put 2 */
double x;
x=num/2;
result=sqrt(x);
printf("num= %d x= %16.lf\n",num,result);
while(abs(x-oldx)>pow(10,-15)){ /* |x-oldx|> pow(10,-15).I am not sure about abs here */
x=oldx; /* i give to x the price of oldx */
printf("x=%lf",x); /* its double so i use lf */
x=(pow(x,2)-num)/2*x; /* #definde f(x) ((x*x-num)/2x) this is it but i wrote it in that way.Maybe i dont know it could be false */
printf("x=%lf",x);
}
printf("x= %lf result= % 16.lf ");
system("pause");
}
答案 0 :(得分:1)
您的代码中存在许多错误:
abs
应为fabs
。while
循环会为每次迭代设置x=oldx
并且oldx
永远不会更改,因此循环永远不会取得任何进展。它应该设置oldx=x
。/2*x
不会根据您的需要除以2*x
,因为*
和/
具有相同的运算符优先级。您需要将其替换为/(2*x)
或/2/x
。此外,当文字常量或简单乘法运算时,无需使用pow
函数计算10 - 1或 x ²。
这是一个完整的解决方案:
#include <stdio.h>
#include <math.h>
int main(void) {
double num = 8; /* i put what ever i want so i put 8 */
double result;
double x;
double oldx;
double residual;
unsigned int 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 - ((x * x - num) / (2 * x));
residual = x - oldx;
} while (fabs(residual) > 1e-15);
printf("x%u=%.16g residual=%.16g\n", iterations, x, residual);
return 0;
}