Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <stdio.h>
- using namespace std;
- double bisection(double,double,double);
- int sign(double);
- double fun(double);
- double derivative(double);
- double newton_raphson(double,double,int);
- int setMax_it();
- double setEps();
- double setStart();
- double setLeft();
- double setRight();
- int main()
- {
- cout<<"Metoda Bisekcji:"<<endl<<endl;
- double left=setLeft();
- double right=setRight();
- double eps=setEps();
- cout<<"Miejsce zerowe funkcji x^3+x-1 to: "<<bisection(left,right,eps)<<endl;
- cout<<"Metoda Newtona-Raphsona:"<<endl<<endl;
- int max_it=setMax_it();
- double start=setStart();
- eps=setEps();
- cout<<endl;
- cout<<"Miejsce zerowe funkcji x^3+x-1 to: "<<newton_raphson(start,eps,max_it)<<endl;
- return 0;
- }
- double setLeft()
- {
- double x;
- cout<<"Podaj lewa granice przedzialu: ";
- cin>>x;
- return x;
- }
- double setRight()
- {
- double x;
- cout<<"Podaj prawa granice przedzialu: ";
- cin>>x;
- return x;
- }
- double setStart()
- {
- double x;
- cout<<"Podaj argument startowy: ";
- cin>>x;
- return x;
- }
- double setEps()
- {
- double x;
- cout<<"Podaj epsilon: ";
- cin>>x;
- return x;
- }
- int setMax_it()
- {
- int max_it;
- cout<<"Podaj maksymalna liczbe iteracji: ";
- cin>>max_it;
- return max_it;
- }
- double derivative(double x)
- {
- return 3*x*x+1;
- }
- double fun(double x)
- {
- return (pow(x,3)+x-1);
- }
- int sign(double x)
- {
- if (x > 0)
- return 1;
- if (x < 0)
- return -1;
- return 0;
- }
- double bisection(double a,double b,double eps)
- {
- if (sign(fun(a))==sign(fun(b)))
- {
- cout << "Wartosci funkcji w punktach a i b maja taki sam znak"<<endl;
- return NAN;
- }
- for(;;)
- {
- double x=(a+b)/2;
- if(abs(fun(x))<=eps)
- return x;
- if(b-a<=eps)
- return x;
- if(sign(fun(x))!=sign(fun(a)))
- b=x;
- else
- a=x;
- }
- }
- double newton_raphson(double start,double eps,int max_it)
- {
- for(int i=0; i<=max_it; i++)
- {
- if(abs(fun(start))<=eps)
- return start;
- double xn=start-(fun(start)/derivative(start));
- if(abs(xn-start)<=eps)
- return xn;
- start=xn;
- }
- cout<<"Podano niepoprawny punkt startowy"<<endl;
- return NAN;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement