Localizing Newton's root finder

Ok so i have a function which I need to find the root closest to x=100.
The function is f(x)=x-tan(x)

So far I cannot figure out how to localize the program around x=100

this is my code thus far (note i had to change tan(x) to arctan because my program couldn't take it for some reason)
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

double root_nm(void(*)(double, double&, double&), double, double, int&);
void fzero(double, double&, double&);

int main()
{
double x, root, eps;
int flag;
cout.setf(ios::fixed | ios::showpoint);
cout.precision(5);

x = 99; // starting poin
eps = 1.0e-2;

root = root_nm(fzero, x, eps, flag);

if (flag == 0 ) cout << " no root found, try to change x1" << endl;
else
{ cout << " iterations" << " root" << endl;
cout << setw(7) << flag << setw(14) << root << endl;}
system ("pause");
return 0;
}

void fzero(double x, double& fx, double& fpx)
{

fx = atan(x)-x;
fpx= (1/(1+x*x))-1.0;
}



double root_nm(void(*f)(double, double&, double&),
double x, double eps, int& flag)

{
double fx, fpx, xc;
int i, iter=1000;
i = 0;
do {
i = i + 1;
f(x,fx,fpx);
xc = x - fx/fpx;
x = xc;
if(i >= iter) break;
} while (fabs(fx) >= eps);

flag = i;
if (i == iter) flag = 0;
return xc;
}
If it helps, I keep getting as my root.
Bump
If your getting zero every time then its working.
The solution to atan(x)-x = 0 is x = 0
Sorry, I'm not sure why my numbers aren't showing, but i keep getting the number .016 as my root, which is right. But it is only the first root, I need the root closest to 100
I can imagine there could be two problems with this case.

One, the evaluating the function or its derivative may give a result which is infinite, in which case, the program may give a NaN (not a number) error.

Secondly, if the starting point is not very close to the root, the next approximation may be further away, rather than closer.

Try plotting a graph of 1-tan(x) around the range x=101 to 103, and you will see how the slope varies dramatically.

Use the graph to help select a better starting point. I tried 102.0 and the program failed. But with 102.1 it was successful.
Last edited on
Gotcha, Thanks!

I see the issue now.
I suppose I can fix this by making it skip NaN and go to the next iteration.
I'm not sure how to do that?
Topic archived. No new replies allowed.