3
votes

I'm to compile and run this program to solve an equation using the Newton-Raphson algorithm, but the number of iterations in the do-while loop is always 1, which shouldn't be the case.

Code

#include<math.h>
#include<stdio.h>

float fonc(float x){
   float result;
   result=2*(pow(x,3))-x-2;
   return result;
 }

float foncprime(float x){
   float result;
   result= 6*(pow(x,2))-1;
   return result;
}

int main(void)
{
   long double x1,x0;
   float eps;
   eps=0.5*pow(10,-4);
   x0=1;
   x1=1;
   int i=0;
   do
   {
      x0=x1;
      x1=x0-(fonc(x0)/foncprime(x0));
      i++;

   }
   while(x1-x0>eps);
   printf("%d",i);
}
3
Don't get in the habit of using pow to compute integer exponentiations. Use x*x for x squared, x*x*x for x cubed, and 5E-5 for 5/100000 (or 0.5E-4, if you prefer.) pow is a lot slower and sometimes slightly less accurate. - rici
@rici I appreciate your advice will never forget it THANK YOU . - user3396807

3 Answers

3
votes

You should probably check while (fabs(x1-x0) > eps).

2
votes

You have assigned x1 to x0 just before the while loop test so the test is 0>eps which will always be false hence it exits the loop on the first iteration.

1
votes

Change:

   while(x1-x0>eps);

to:

   while(fabs(x1-x0)>eps);