Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <iostream>
- #include <cmath>
- using namespace std;
- double f(double x)
- {
- return x*x - 3;
- }
- double derivative(double x)
- {
- return 2*x;
- }
- double sign(double f)
- {
- return f >= 0;
- }
- double newton(double a, double b, double eps)
- {
- double x = (a + b) / 2;
- double x1 = 0;
- for(; abs(x-x1) > eps;)
- {
- x1 = x;
- if (derivative(x) == 0 && f(x) != 0)
- {
- cout << "Newton Method can not be used!";
- return 0;
- }
- if (derivative(x) == 0 && f(x) == 0)
- {
- cout << "Newton Method = 0";
- return 0;
- }
- x = x - f(x) / derivative(x);
- }
- return x;
- }
- void iter(double a, double b, double eps)
- {
- double x = (a + b) / 2;
- for (int i = 0;; ++i)
- {
- double x0 = x + f(x);
- if (x == x0)
- {
- cout << "Iteration method = " << x << endl;
- return;
- }
- if (i == 10) {
- if (abs(x0-x) < eps)
- {
- cout << "Iteration method priblizitelno = " << (x0 + x) / 2 << endl;
- return;
- }
- else
- {
- cout << "Iteration method ne imeet resheniya" << endl;
- return;
- }
- }
- x = x0;
- }
- }
- double bisec(double a, double b, double eps)
- {
- double res = (a + b)/2;
- for (; abs(b-a) > eps; )
- {
- if (sign(f(a)) == sign(f(res)))
- {
- a = res;
- }
- else
- {
- b = res;
- }
- if (f(res) == 0)
- {
- return res;
- }
- res = (a + b) / 2;
- }
- return res;
- }
- int main(int argc, char* argv[])
- {
- double a, b, eps;
- cout << "Enter a, b and eps" << endl;
- cin >> a >> b >> eps;
- cout << "Bisection method result: " << bisec(a, b, eps) << endl;
- cout << "Iterazii method result: " << iter(a, b, eps) << endl;
- cout << "Newtona method result: " << newton(a, b, eps) << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement