I am writing a program that solves for the root of a polynomial using newton raphson method.Newton-Raphson has the following algorithm:
• Make one initial guess, x0
• Repeat the following step to get a new
guess, x[k+1], from the old guess, x[k]
-Compute x[k+1] from the following equation
x[k+1] = x[k] - f(x[k])/f'(x[k])
• Continue iteration until the value of x[k+1]
and/or f(x[k+1]) is sufficiently accurate
If you try it with this polynomial: x^2 - 5x + 2 with initial guess of 4 at 3rd iteration you should get a root of 4.561553..
My code below runs but don't give correct results.. Please help me .. Thank you so much.
Here is the sample using the function above:
Enter the power of the equation: 2
Enter the coefficient of x^2: 1
Enter the coefficient of x^1: -5
Enter the constant term: 2
Enter a guess: 4
Set maximum number of iteration: 3
4
1.#INF00000000
-1.#IND0000000
-1.#IND0000000
The approximate root is -1.#IND0000000
|
This answer is very far from reality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <iostream>
#include <math.h>
using namespace std;
const int MAX = 1000;
int p;
double f(double);
double df(double);
double coeff[MAX], dcoeff[MAX];
double newtonraphson(double);
int main()
{
double x[MAX];
int imax, icount, i;
double guess, tol;
//Get Function
cout << "Enter the power of the equation: ";
cin >> p;
for(int i = p; i > 0; i--)
{
cout << "Enter the coefficient of x^" << i << ": ";
cin >> coeff[i];
}
cout << "Enter the constant term: ";
cin >> coeff[0];
cout << endl;
//Final inputs
cout << "Enter a guess: ";
cin >> x[0];
cout << "Set maximum number of iteration: ";
cin >> imax;
x[1] = newtonraphson(x[0]);
for(i = 1; i < imax; i++)
{
x[i+1] = newtonraphson(x[i]);
}
//outputs the approximate root
cout << x[0] << endl;
for(i = 0; i < imax; i++)
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(20);
cout << x[i+1] << endl;
}
cout << "The approximate root is: ";
cout << x[imax-1];
cin.get();
cin.get();
return 0;
}
double f(double x)
{
int i;
double s = 0;
for(i = 0; i <= p; i++)
{
s += coeff[i] * pow(x, i);
}
return s;
}
double df(double x)
{
int i;
double val = 0;
for(i = 0; i < p; i++)
{
val += (dcoeff[i] * pow(x, i));
}
return val;
}
double newtonraphson(double xo)
{
return xo - f(xo)/df(xo);
}
|