Christian Christian - 3 months ago 9
C++ Question

I'm a beginner, trying to write a function that finds the root of an array function

I've been working for a couple hours trying to figure out what I'm doing wrong. All I need to do is find one root from a polynomial represented by an array using Newton's method. The two functions (polyval and polyder) seem to be giving me the right answers, and I feel that the main code is correctly doing Newton's method. I was hoping someone experienced could give me some advice.

#include <iostream>
#include <cmath>

using namespace std;

float polyval(float*, int, float);
void polyder(float*, int, float*);

int main(void) {
int n;
float x=-1,f;
float tol=pow(10,-5);

cout << "Enter polynomial order:" << endl;
cin >> n;

float* p=new float[n+1];
float* dp=new float[n];

cout << "Enter coefficients, starting with the highest power:" << endl;
for (int k=0;k<n+1;k++) {
cin >> p[k];
}

polyder(p,n,dp);
f=polyval(p,n,x);

while (fabs(f)>tol) {
x=x-f/polyval(dp,n,x);
f=polyval(p,n,x);
cout << x << endl;
cout << f << endl;
}

cout << "A real root is at x= " << x << endl;
cout << "To verify: p(" << x << ") = " << polyval(p,n,x) << endl;

return 0;
}

float polyval(float* p, int n, float x) {
float px;
px=0;

for (int k=0;k<n+1;k++) {
px=px+p[k]*pow(x,n-k);
}

return px;
}

void polyder(float* p, int n, float* dp) {
for(int k=0;k<n;k++) {
dp[k] = p[k+1] * (k+1);
}
}

Answer

Your call to polyval(dp,n,x) will access beyond the allocated space for dp, which has n entries and not the requred n+1.