Hey all, I'm new to C++ and programming in general. I'd like to write a program that uses the Newton Raphson method to calculate a root of a polynomial (determined by the user) given an initial guess.
The code all compiles correctly, but for some reason the result I get is wrong. Could someone take a look at this and see what the problem is?
// Program using the Newton Raphson method to find roots of a polynomial.
//
#include <iostream>
#include <cmath>
usingnamespace std;
//Declare function
double NR(double a[10], double start, int iterations);
int main()
{
int n = 0, N = 0;
double coeff[10], seed, result;
// Initialise array
for ( int m=0; m<10; m++){
coeff[m] = 0;
}
//User instructions begin
while (n < 1 || n > 9) {
cout << "What is the degree of your polynomial (enter an integer between 1 and 9)?" << endl;
cin >> n;
}
cout << "Please enter the coefficients of your polynomial (lowest power first):" << endl;
for (int i=0; i<=n; i++) {
cout << "Coefficient of x^" << i << " term:" << endl;
cin >> coeff[i];
}
cout << "Please enter a starting guess for a root of your polynomial:" << endl;
cin >> seed;
while (N < 1) {
cout << "Please enter a valid number of N-R iterations you would like to carry out:" << endl;
cin >> N;
}
result = NR(coeff,seed,N);
//Result
cout << result << " is a root of your polynomial." << endl;
return 0;
}
//Define function
double NR(double a[10], double start, int iterations)
{
// Initialise array
for ( int m=0; m<10; m++){
a[m] = 0;
}
double root = start, function = 0, derivative=0;
// Newton-Raphson algorithm
for( int r=0; r < iterations; r++){
for( int p=1; p<10; p++){
function += a[p]*pow(root,p-1);
}
for ( int q=2; q<10; q++){
derivative += a[q]*pow(root,q-2)*(q-1);
}
root -= (function/derivative);
}
return root;
}