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 :)

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
// Program using the Newton Raphson method to find roots of a polynomial.
//

#include <iostream>
#include <cmath>
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.