I am running code for the Newton Raphson method for any equation in C++. I tried inputting coefficients of the equation but suddenly the loop goes on and on. The "fun" function computes the value of the given equation by the user and "der" computes derivates of that function and passes that value to the main.
Edit: I found an error by using a debugger. The below picture shows the condition. If I input only 3 coefficients the other (10 - 3= 7) elements in the array will be randomly generated by the computer itself. So now my main question is how can I initialize and use array such that it would be m[n] just what the user wants. You can see m[3]= 32765 and I want to automatically close the array after m[2].
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double fun(double x, int m[10], int n) {
double a;
for (int i = 0; i < (n+1); i++)
{
a += m[i]*pow(x,n-i);
}
return a;
}
double der(double x, int m[10], int n) {
double a;
for (int i = 0; i < (n+1); i++)
{
a += (n-i)*m[i]*pow(x,n-1-i);
}
return a;
}
int main() {
int i, n, m[10];
double x, y, E, f1, f2;
double f3;
cout << "Enter numbers and error tolerance " << endl;
cin >> x >> E;
cout << "Enter degree of polynomials (less than 4)" << endl;
cin >> n;
cout << "Enter " << n+1 << " coefficients" << endl;
for ( i = 0; i < (n+1) ; ++i)
{
cin >> m[i];
}
cout << " " << 'i' << setw(14) << 'x' << setw(14) << 'y' << setw(14) << "f3" << endl;
do
{
f1 = fun(x,m,n);
f2 = der(x,m,n);
y = x - (f1/f2);
f3 = fun(y,m,n);
++i;
cout << " " << i << setw(14) << x << setw(14) << y << setw(14) << f3 << endl;
x = y;
}while ( fabs(f3)>E);
cout << "The root is " << y << endl;
return 0;
}