Hi. I really need someone to help me with this.
I have to create a program that solve this equation using Newton's method.
cosx - 0.9 + x*x/3 = 0
This is the code that i've witten. I keep getting error everytime i try to compile the code. Did i wrote the equation correctly for the cos and sine part?
Also, for the 'no of iteration' part, how should i do to make the output becomes 1,2,3,4,.... instead of 1.00000,2.00000,3.00000,...
Code:
#include<stdio.h>
#include<math.h>
double f( double x ) {
return cos(x)-0.9+x*x/3;
}
double diff( double x ) {
return -sin(x)+2*x/3;
}
double newton( double initial ) {
double e = 0.000001 ;//
double x1, x2;
double a;
x2 = initial;
a = 0;
while( 1 ) {
x1 = x2 - f(x2)/diff(x2) ; // The formula
if( fabs(x1-x2) < e ) {
return x1;
} else {
x2 = x1;
a = a+1;
printf( "New value of x is %f.Ends of iteration %f\n", x1, a);
}
printf( "Total no of iteration is %f\n", a);
}
}
int main() {
double x0 = 1.0 ; // initial value of x
printf( "Final answer is x =%f\n", newton(x0));
}