Hello. I am having problems with a program I've written to find the roots of a cubic equation using Newton's Method. The user inputs the coefficients in the expression (real) and an initial guess (real or complex), and the program is supposed to return a root of the function. However, my program works very erratically. For instance, I input the equation "x^3 - x = 0" and an initial guess of (1.2, 1.5) and my program returned the root of 0 in 11 iterations. I entered the same equation and guess later without even closing the dos box, and my program returned "In 1000 iterations, no solution was found." It is very rare that my program returns a root, and when it does, it only seems to be able to get the root when it is zero. Any insight would be appreciated.
This is my header file to implement newton's method:
#include <iostream>
#include <math.h>
#include <complex>
using namespace std;
const int nmax = 1000;
const double error = 1.0e-6;
int n = 1;
double a, b, c, d;
inline complex<double> f(complex<double> x) {return a*x*x*x + b*x*x + c*x + d;} //cubic polynomial
inline complex<double> fprime(complex<double> x) {return 3.0*a*x*x + 2.0*b*x + c;}//derivative of polynomial
complex<double> newton (complex<double>& x)
{
while ((abs(x) > error) && (n < nmax + 1))
{
x -= (f(x)/fprime(x));
n++;
}
return n;
}
and here is a snippet of code where I implement it:
complex<double> x;
cout << "SOLVING A CUBIC EQUATION ax^3 + bx^2 + cx + d USING NEWTON'S METHOD\n\n";
cout << "Enter a, b, c, and d.\n\n";
cin >> a >> b >> c >> d;
cout << "Give an initial approximation to a root.\n";
cin >> x;
newton(x); // see complex_newton.h
if (n > nmax)
cout << "In " << nmax << " iterations, no solution was found.\n";
else
cout << "The solution is " << x << " and it was found in " << n << " iterations.\n";
Thank you!