Search code examples
c++newtons-method

Newton Tangent method in C++


So I have to write a Newton tangent programm with the starting point 1.0. I have to show the iteration count and the root that result at the end. If I type in 100 for U0, the root/result should be 2,499204 but somehow it shows me 17.3333 and just one iteration count which i dont think is the correct result.

I don't know where my mistake is, it would be great if someone could point it out as i'm just a beginner.

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

double U0;
const double K = 0.001; //constant
const double R = 1000; //Widerstand
const double ALPHA = 5; //Exponent
const double epsilon = 0.0000001; //epsilon

double f(double u);
double fstrich (double u);
double f(double u)
{
    return (-U0+R*K*pow(u,ALPHA)+ u); //U0+R*K*U^a + u
    }
double fstrich (double u)
{
    return ALPHA*R*K*pow(u,ALPHA-1)+ 1;
    }


int main()
{
    double i=0; //iteration
    double xn = 1.0; //starting point
    double xn1; //xn+1

    cout << "Geben Sie eine Spannung U0 zwischen -1000 und 1000 ein: ";
    cin >> U0;
    cout << "\n";

    do
    {
        i++;
        xn1 = xn - f(xn)/fstrich(xn);
        xn=xn1;
        cout<< "Iteration count: "<<i << " " << xn<< " " <<endl;

    } while (fabs(xn-xn1)>epsilon);
    cout <<"The root is " <<fixed <<setprecision(8)<< xn1 <<endl;


    return 0;
}

Solution

  • fabs(xn-xn1)>epsilon is always false as prior code does xn=xn1; @user4581301


    Changing to ...

    double delta;  // add
    do
    {
        i++;
        xn1 = xn - f(xn)/fstrich(xn);
        delta = xn-xn1; // add
        xn=xn1;
        cout<< "Iteration count: "<<i << " " << xn<< " " <<endl;
    
    //} while (fabs(xn-xn1)>epsilon);
    } while (fabs(delta)>epsilon);
    

    ... xn1 converged quickly to

    2.49920357...