user3396807
user3396807

Reputation:

Newton-Raphson Algorithm

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

Upvotes: 2

Views: 1219

Answers (3)

barak manos
barak manos

Reputation: 30136

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

Upvotes: 2

Joseph Quinsey
Joseph Quinsey

Reputation: 9962

Change:

   while(x1-x0>eps);

to:

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

Upvotes: 1

Neil Hampton
Neil Hampton

Reputation: 1883

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.

Upvotes: 2

Related Questions