-1

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].

enter image description here

#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;
}

The below picture shows the result: enter image description here

Auberron
  • 107
  • 2
  • 7
    `double a;` -- You didn't initialize it, anything might happen. The variables declared in a function body must be initialized since they're a type of `auto` storage class. – Rohan Bari May 26 '21 at 13:31
  • 1
    `double a = 0` or some value. – Rohan Bari May 26 '21 at 13:38
  • @Auberron `double a = 0;` .. – sagi May 26 '21 at 13:38
  • 2
    @Auberron Not the downvoter, but it's obvious. Have you tried debugging out the program before posting it? If so, then add those details here. *Why the program does not stop?* can have ambiguously many reasons, it is not possible to predict what could be the exact reason when sufficient information is not provided. – Rohan Bari May 26 '21 at 13:57
  • Thanks Rohan. I will also add them. – Auberron May 26 '21 at 14:01

0 Answers0