So I'm writing a program that demonstrates Newton's method to find a root of an equation. It outputs the estimated value of the root, the the true error and empirical error. After trying to run the program, the true error and estimated error were outputting "-nan(ind)". I stepped through my program and found out that the original function for Newton's method was returning this "-nan(ind)". What is "-nan(ind)" and how do I avoid it in this program?
float newton(int count, float aval, float bval)
{
count++; //Increase count to avoid going past contraint
float cval = (aval + bval) / 2; //Get midpoint of interval
float estroot = cval; //Set estimated root equal to midpoint
cout << estroot << endl; //Output was root is estimated to be right now
if (count == 20) //If constraint is reached, end recursion
{
return estroot;
}
elseif (equation(aval) * equation(cval) < 0) //If root is in between left value and midpoint,
//recur with that interval
{
estroot = newton(count, aval, cval);
}
elseif (equation(cval) * equation(bval) < 0) //If root is in between midpoint and right value,
//recur with that interval
{
estroot = newton(count, cval, bval);
}
}
int main()
{
char end;
float aval = 1.0; //Initial a value
float bval = 4.0; //Initial b value
float realroot = 2.0; //Real root
float estroot;
int count = 0; //count variable to make sure number of iterations does not exceed 20
estroot = newton(count, aval, bval); //Function to find root
float trueerr;
trueerr = realroot - estroot;
float emperr;
emperr = equation(estroot) / derivative(estroot);
cout << "True error = " << trueerr << "\nEmpirical error = " << emperr << endl;
cin >> end; //Pauses program so user can read output
}
NaN is "not a number", possibly resulting from some mathematical faux pas like dividing by 0, or using something undefined. Difficult to tell without full code.
You appear to be implementing the bisection method, not the Newton(-Raphson) method for root-finding. I would expect to see the latter involving a function and its derivative, not your "empirical error".
Can we see your equation( ) function, please: the function whose root you are trying to find.
Also note that your newton function won't know what to return if equation(cval) is exactly equal to 0 - which, of course, is the root you are seeking.
Is there any reason you are using recursion rather than the more straightforward iteration?
float equation(float value)
{
float output;
output = 2 * (value * value) - 8; //Equation that we are trying to find root for, can be modified
return output; //return output of equation
}
float derivative(float value)
{
float output;
output = 4 * value;
return output;
}
Here's the code for the equation and it's first derivative. I'm using recursion even though it's less straightforward because I honestly need more practice in recursion and this gave me a great excuse to try it.