### Newton Raphson to find roots of polynomial

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?

Many thanks :)

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475`` ``````// Program using the Newton Raphson method to find roots of a polynomial. // #include #include using namespace 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; }``````
Topic archived. No new replies allowed.