chemmisol 0.1
Loading...
Searching...
No Matches
regula_falsi.h
Go to the documentation of this file.
1#include <functional>
2#include <stdexcept>
3#include <iostream>
4#include <math.h>
5#include <string>
6
14namespace chemmisol {
15
19 template<typename T>
21 private:
22 T a_0;
23 T b_0;
24
25 std::function<T(const T&)> f;
26
27 T solve_iter(T a, T b, T f_a, T f_b, std::size_t n) const;
28 T solve_eps(T a, T b, T f_a, T f_b, T eps) const;
29
30 public:
42 RegulaFalsi(T a, T b, std::function<T(const T&)> f) :
43 a_0(a), b_0(b), f(f) {
44 }
45
58 T solve_iter(std::size_t n) const;
59
72 T solve_eps(T eps) const;
73 };
74
75 template<typename T>
76 T RegulaFalsi<T>::solve_iter(std::size_t n) const {
77 T f_a = f(a_0);
78 T f_b = f(b_0);
79 if(f_a*f_b > 0)
80 throw std::logic_error(
81 " f(a_0) = " + std::to_string(f_a) +
82 " and f(b_0) " + std::to_string(f_b) +
83 " should be of opposite signs. (a_0=" +
84 std::to_string(a_0) + ", b_0=" + std::to_string(b_0) + ")"
85 );
86 return solve_iter(a_0, b_0, f_a, f_b, n);
87 }
88
89 template<typename T>
90 T RegulaFalsi<T>::solve_iter(T a, T b, T f_a, T f_b, std::size_t n) const {
91 if(f_a == f_b)
92 return a;
93 T c = (a * f_b - b * f_a) / (f_b - f_a);
94 if(n==0)
95 return c;
96 T f_c = f(c);
97 if(f_c == 0.0)
98 return c;
99 if(f_c * f_a < 0)
100 return solve_iter(a, c, f_a, f_c, n-1);
101 return solve_iter(c, b, f_c, f_b, n-1);
102 }
103
104 template<typename T>
106 T f_a = f(a_0);
107 T f_b = f(b_0);
108 if(f_a*f_b > 0)
109 throw std::logic_error(
110 "f(a_0) = " + std::to_string(f_a) +
111 " and f(b_0) " + std::to_string(f_b) +
112 " should be of opposite signs. (a_0=" +
113 std::to_string(a_0) + ", b_0=" + std::to_string(b_0) + ")"
114 );
115 return solve_eps(a_0, b_0, f_a, f_b, eps);
116 }
117
118 template<typename T>
119 T RegulaFalsi<T>::solve_eps(T a, T b, T f_a, T f_b, T eps) const {
120 if(f_a == f_b)
121 return a;
122 T c = (a * f_b - b * f_a) / (f_b - f_a);
123 T f_c = f(c);
124 if(std::abs(f_c) < eps)
125 return c;
126 if(f_c * f_a < 0)
127 return solve_eps(a, c, f_a, f_c, eps);
128 return solve_eps(c, b, f_c, f_b, eps);
129 }
130}
Definition regula_falsi.h:20
RegulaFalsi(T a, T b, std::function< T(const T &)> f)
Definition regula_falsi.h:42
Definition chemmisol.h:31