-1

I'm writing some code as part of a few assignment exercises to learn C programming from absolute basics, and I've run into a problem, which is probably quite simple to solve, but I'm completely stuck! I'm writing a program to implement a basic Newton's method for differentiation. Whenever I input an initial value to the scanf(), the program simply stops, doesn't return anything, terminate or freeze. Any help would be great. Here is my code to start with:

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

//function to be used f(x) = cos(x)-x^3

//f'(x) = -sin(x)-3x^2

int main()
{
  double x, xold;
  printf("Enter an initial value between 0 and 1\n");
  scanf("%lf",&xold);
  double eps = 1e-12;
   x = xold - ((cos(xold)-pow(xold,3))/(-(sin(xold)-(3*pow(xold,2)))));
    while (fabs(x-xold)>eps)
    {
    x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));
    }
    printf("The answer is %.12lf",x);
    return 0;
};
alexheslop1
  • 115
  • 3
  • 9

2 Answers2

2

In your while loop:

x = xold - ((cos(xold)-pow(xold,3))/(-sin(xold)-(3*pow(xold,2))));

the value of the = right operand is always the same, how could you exit the loop once you enter it?

ouah
  • 134,166
  • 14
  • 247
  • 314
  • Ah okay, I'm trying to get it to change the new x into the xold, and then retry it. Any idea how i'd do that? Sorry, this is literally the first time I've done coding haha – alexheslop1 Jul 04 '14 at 19:51
0

Actually the thing is you are not updating your xold variable. Try the below modified code for your problem, see if I have done correctly:

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


int main()
{
    double x, xold;
    printf("Enter an initial value between 0 and 1\n");
    scanf("%lf",&x);
    double eps = 1e-12;

    x = x - ((cos(x)-pow(x,3))/(-(sin(x)-(3*pow(x,2)))));
    while (fabs(x - xold)>eps)
    { 
        xold = x;
        x = x - ((cos(x)-pow(x,3))/(-sin(x)-(3*pow(x,2))));
    }
    printf("The answer is %.12lf\n",x);

    return 0;
}
mSatyam
  • 489
  • 6
  • 23