具有 sqrt、abs 和 c 上的导数的方程

Equation having sqrt ,abs and the derivative on c

首先,我想告诉你英语不是我的天性语言,所以可能是我不会表达的词或意思 right.The 现在的问题是我最近做了一个练习,问题是使用sqrt.Anyway 的 Newton-Raphson 方法,我想这个(sqrt)我已经做到了我不确定 it.I 不能做到 derivative.Also,我想我的代码有一些错误如果你可以解决它我会 greatful.The 等式是

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");
}

你的代码中有很多错误:

  1. abs 应该是 fabs.
  2. while 循环会为每次迭代保持设置 x=oldx,而 oldx 永远不会改变,因此循环永远不会取得任何进展。它真的应该设置 oldx=x.
  3. /2*x 不会按您的要求除以 2*x,因为 */ 具有相同的运算符优先级。您需要将其替换为 /(2*x)/2/x.
  4. 在每一步中,您都在计算 xₙ₊₁ = f(xₙ) / fʹ(xₙ) ,但正确的公式是 xₙ₊₁ = xₙf(xₙ) / fʹ(xₙ).

此外,不需要使用 pow 函数来计算 10⁻¹⁵ 或 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;
}