C++ Bc. 29 cpp
(přesměrováno z C plus plus Bc. 29 cpp)
#include <iostream>
#include <cmath>
#include <string>
struct Chyba
{
template <typename T> Chyba(T t) : text(t) {}
std::string text;
};
typedef double (*Funkce)(double);
double tetivy(Funkce f, double a, double b, double tol=1e-12) throw (Chyba);
double test(double x)
{
return std::sin(4*x*x - x - 0.3);
}
int main()
{
try
{
double d =tetivy(test, -1, 1);
std::cout << "Aproximace korene x = " << d
<< " f(x) = " << test(d) << "\n";
}
catch(Chyba chyba)
{
std::cout << chyba.text << "\n";
}
}
double tetivy(Funkce f, double a, double b, double tol) throw (Chyba)
{
double fa = f(a);
double fb = f(b);
double x, fx;
if (fa*fb > 0) throw Chyba("Neni splnena podminka f(a)*f(b) < 0\n");
if (std::abs(a - b) < tol) return a;
do
{
x = (b*fa - a*fb)/(fa - fb);
fx = f(x);
if (fa*fx > 0)
{
a = x;
fa = fx;
}
else
{
b = x;
fb = fx;
}
}
while (std::abs(fx) > tol && std::abs(a - b) > tol);
return x;
}
[ Zpět ]