Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <cmath>
- bool sgn(double var)
- {
- return var >= 0.0f;
- }
- void bisection(double(*f)(double), double &a, double &b, double &aVar, double &bVar)
- {
- double c = (a + b) / 2;
- double var = f(c);
- if (sgn(aVar) == sgn(var))
- {
- a = c;
- aVar = var;
- }
- else if (sgn(bVar) == sgn(var))
- {
- b = c;
- bVar = var;
- }
- }
- double sieczne(double a, double b, double aVar, double bVar)
- {
- return b - ((bVar)*(b - a) / ((bVar)-(aVar)));
- }
- bool checkVar(double var, double eps)
- {
- if (abs(var) <= eps)
- return true;
- return false;
- }
- double wyznaczMiejsceZerowe(
- double(*f)(double), // funkcja której zera szukamy w [a, b]
- double a, // lewy koniec przedziału
- double b, // prawy koniec przedziału
- int M, // maksymalna dozwolona liczba wywołań funkcji f
- double eps, // spodziewana dokładność zera
- double delta // wystarczający błąd bezwzględny wyniku
- )
- {
- double static startSieeczne = (1.0f / 64.0f);
- double varA = f(a);
- if (checkVar(varA, eps))
- return a;
- double varB = f(b);
- if (checkVar(varB, eps))
- return b;
- do {
- if (sgn(varA) == sgn(varB))
- {
- double c = sieczne(a, b, varA, varB);
- varA = varB;
- a = b;
- varB = f(c);
- b = c;
- }
- else
- {
- if (abs(a - b) <= startSieeczne)
- {
- double c = sieczne(a, b, varA, varB);
- varA = varB;
- a = b;
- varB = f(c);
- b = c;
- }
- else
- {
- bisection(f, a, b, varA, varB);
- }
- }
- } while (abs(a - b) > delta && !checkVar(varB, eps));
- return b;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement