Untitled
raw download clone
CPP
views 28
,
size 1454 b
#include <iostream>
#include <cmath>

using namespace std;

double f(double x)
{
    return x*x-5;
}

double fprim(double x)
{
    return 2*x;
}

double bisect(double a, double b, double eps)
{
    int i=0;
    double fa,fb,s,fs;
    fa = f(a);
    fb = f(b);
    if(abs(fa)<eps) return a;
    if(abs(fb)<eps) return b;
    if(fa*fb<0)
    {
        s=(a+b)/2;
        fs=f(s);
        while(abs(b-a)> eps && abs(fs) > eps)
        {
            if(fa*fs<0) {b=s; fb=f(b);}
            if(fb*fs<0) {a=s; fa=f(a);}
            s=(a+b)/2;
            fs=f(s);
            cout << s << endl;
            i++;
        }
        cout << "Liczba krokow = " << i << endl;
        return s;
    }
    else return -1;
}


bool newton(double &x, double eps, int MAX)
{
    double fx,fprimx,xi;
    int i=0;
    fx = f(x);
    fprimx = fprim(x);
    xi = x-(fx/fprimx);
    double r = x - xi;
    while(abs(fx)>eps && abs(r) > eps && i<MAX)
    {
        xi = x-(fx/fprimx);
        r = x - xi;
        cout << xi << endl;
        x = xi;
        fx = f(x);
        fprimx = fprim(x);
        i++;
    }
    cout << "Liczba krokow = " << i << endl;
    if(i>MAX) return false;
    else return true;
}
int main()
{
    double a=0,b=5,eps=1E-8,x=5;
    //cout << "Wynik bisekcji = " << bisect(a,b,eps) << endl;
    newton(x,eps,100);
    cout << "Wynik Newton = " << x << endl;
    return 0;
}
close fullscreen
Login or Register to edit or fork this paste. It's free.