Newton's Method

For the equation:

xsinx = cosx

There are an infinite number of answers. To find them by iteration, you must use newton's method where:

x(n+1) = x(n) - (f(x)/(f'x))

#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;

int main ()
{
ofstream file ("output/newt_root.dat");
for (int n=0; n<10000; n++){
double guess = 0.5 + (n*3);
double V = guess - ((guess*(sin(guess))-cos(guess))/(2*sin(guess)+(guess*cos(guess))));
int i=1;
while (i<100){
V = V - ((V*(sin(V))-cos(V))/(2*sin(V)+(V*cos(V))));
i += 1;
}
file<<n<<"\t"<<V<<endl;
}
file.close();
return 0;
}


The data in my output is being given at best as 6 digits, but I would like to extend that accuracy. Does this mean I need to change the variable type (ie long double?) so that it will have more memory to store the characters?

Thanks
JM COOPER
Last edited on
I wonder if you're loosing precision because you're doing 100 iterations. You might be getting a more precise answer and then losing precision to rounding errors as you go. Try this instead (note that I've replaced the while loop with a for loop:
1
2
3
4
5
for (int i=1; i<100; ++i) {
    double newV = V - ((V*(sin(V))-cos(V))/(2*sin(V)+(V*cos(V))));
    if (fabs(newV-V) < 1E-8) break;
    V = newV;
}

This code will break out of the loop if you converge to within 10^-8, or if you hit 100 iterations.
Topic archived. No new replies allowed.