Skip to content

Instantly share code, notes, and snippets.

Created May 5, 2013 18:15
Show Gist options
  • Save anonymous/5521644 to your computer and use it in GitHub Desktop.
Save anonymous/5521644 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
template <class T>
struct Fun {
const T operator()(T x) {
return std::log(x+2) - 2*x*x + 1;
}
T d1(T x) {
return 1.0 / (x+2) - 4*x;
}
T d2(T x) {
return - 1.0 / ((x+2.0)*(x+2.0)) - 4.0;
}
};
template <class T>
std::pair<T, unsigned> bisection (T a, T b, T eps = 1e-6, unsigned it_bnd = 10000) {
if (a > b) {
std::swap(a, b);
}
Fun<T> f;
if (f(a) * f(b) > 0) {
throw std::runtime_error("No solution in this interval");
}
unsigned it_cnt = 0;
for (; std::abs(b - a) >= eps && it_bnd > it_cnt; ++it_cnt) {
T c = (a + b) / 2.0;
if (f(a) * f(c) <= 0.0) {
b = c;
} else {
a = c;
}
}
T fa = f(a), fx = f((a + b) / 2.0), fb = f(b);
if ( (fa > fx && fx > fb) || (fa < fx && fx < fb) ) {
return std::make_pair((a + b) / 2.0, it_cnt);
} else {
std::runtime_error("Znaleziono asymptote pionowa!");
}
}
template <class T>
std::pair<T, unsigned> tangents (T a, T b, T eps = 1e-6, unsigned it_bnd = 10000) {
if (a > b) {
std::swap(a, b);
}
Fun<T> f;
if (f(a) * f(b) > 0) {
throw std::runtime_error("No solution in this interval");
}
T xk;
if (f(a) * f.d2(a) > 0) {
xk = a;
} else if (f(b) * f.d2(b) > 0) {
xk = b;
} else {
throw std::runtime_error("Przedzial nie spelnia zalozen!");
}
T m = std::min(std::abs(f.d1(a)), std::abs(f.d1(b)));
unsigned it_cnt = 0;
for (; std::abs(f(xk)) / m >= eps && it_bnd > it_cnt; ++it_cnt) {
xk = xk - (f(xk) / f.d1(xk));
}
if (xk >= a && xk <= b) {
return std::make_pair(xk, it_cnt);
} else {
std::runtime_error("Znaleziono asymptote pionowa!");
}
}
template<class T>
void start (T eps) {
std::pair<T, unsigned> sol;
try {
sol = bisection<T>(-0.8, -0.7, eps);
cout << "Bisekcje:\t" << sol.first << "\n";
cout << "Ilosc iteracji:\t" << sol.second << "\n\n";
} catch (std::runtime_error e) {
cout << e.what() << "\n\n";
}
try {
sol = tangents<T>(-0.8, -0.7, eps);
cout << "Styczne:\t" << sol.first << "\n";
cout << "Ilosc iteracji:\t" << sol.second << "\n\n";
} catch (std::runtime_error e) {
cout << e.what() << "\n\n";
}
}
int main () {
cout.setf(std::ios::adjustfield);
//cout.setf(ios::fixed);
cout.precision(10);
start<double>(1e-11);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment