Search code examples
cderivativesqrt

Equation having sqrt ,abs and the derivative on c


First, i would like to tell you that english isnt my nature language so maybe a word or meaning i am not express it right.The problem now is i recently did one exercise and the question was to use the Newton-Raphson method for sqrt.Anyway, i think this(sqrt) i have done it i am not sure about it.I couldnt do the derivative.Also,i think i have some mistakes on my code if you could fix it i would be greatful.The equation is

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

Solution

  • There are numerous mistakes in your code:

    1. abs should be fabs.
    2. The while loop keeps setting x=oldx for each iteration and oldx never changes, so the loop never makes any progress. It should really set oldx=x.
    3. /2*x does not divide by 2*x as you require, because * and / have the same operator precedence. You need to replace it with /(2*x) or /2/x.
    4. At each step, you are calculating xₙ₊₁ = f(xₙ) / fʹ(xₙ), but the correct formula is xₙ₊₁ = xₙf(xₙ) / fʹ(xₙ).

    In addition, there is no need to use the pow function to calculate 10⁻¹⁵ or x² when a literal constant or a simple multiplication will do.

    Here is a complete solution:

    #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;
    }