1

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;
}
nrerf
  • 15
  • 3
  • 2
    The programmer's secret weapon is the debugger. With a debugger you can step through the code at your pace and watch what the program does as it does it. As soon as you see the program deviate from the expected (sets a variable to the wrong value, takes the wrong path, or does something really weird) usually you've found a bug. Might take a bit more thinking to figure out why it's a bug and how to fix it, but at least you know where it is and what it should have done instead. – user4581301 Dec 03 '20 at 02:22
  • 3
    After `xn = xn1;` how can `xn - xn1` not be a 0? – user4581301 Dec 03 '20 at 02:25
  • @user4581301 yeah i'm new to using a debugger, i should look more into it thanks – nrerf Dec 03 '20 at 07:02

1 Answers1

2

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...
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256