NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
Secant.hpp
Go to the documentation of this file.
1
33#pragma once
34
35#include <cmath>
36#include <functional>
37#include <utility>
38
39#include "NumCpp/Core/Types.hpp"
41
42namespace nc::roots
43{
44 //================================================================================
45 // Class Description:
48 class Secant : public Iteration
49 {
50 public:
51 //============================================================================
52 // Method Description:
58 Secant(const double epsilon, std::function<double(double)> f) noexcept :
59 Iteration(epsilon),
60 f_(std::move(f))
61 {
62 }
63
64 //============================================================================
65 // Method Description:
72 Secant(const double epsilon, const uint32 maxNumIterations, std::function<double(double)> f) noexcept :
73 Iteration(epsilon, maxNumIterations),
74 f_(std::move(f))
75 {
76 }
77
78 //============================================================================
79 // Method Description:
82 ~Secant() override = default;
83
84 //============================================================================
85 // Method Description:
92 double solve(double a, double b)
93 {
95
96 if (f_(a) > f_(b))
97 {
98 std::swap(a, b);
99 }
100
101 double x = b;
102 double lastX = a;
103 double fx = f_(b);
104 double lastFx = f_(a);
105
106 while (std::fabs(fx) >= epsilon_)
107 {
108 const double x_tmp = calculateX(x, lastX, fx, lastFx);
109
110 lastFx = fx;
111 lastX = x;
112 x = x_tmp;
113
114 fx = f_(x);
115
117 }
118
119 return x;
120 }
121
122 private:
123 //============================================================================
124 const std::function<double(double)> f_;
125
126 //============================================================================
127 // Method Description:
136 static double calculateX(double x, double lastX, double fx, double lastFx) noexcept
137 {
138 const double functionDifference = fx - lastFx;
139 return x - fx * (x - lastX) / functionDifference;
140 }
141 };
142} // namespace nc::roots
Iteration(double epsilon) noexcept
Definition Iteration.hpp:52
const double epsilon_
Definition Iteration.hpp:112
void resetNumberOfIterations() noexcept
Definition Iteration.hpp:92
void incrementNumberOfIterations()
Definition Iteration.hpp:101
double solve(double a, double b)
Definition Secant.hpp:92
~Secant() override=default
Secant(const double epsilon, const uint32 maxNumIterations, std::function< double(double)> f) noexcept
Definition Secant.hpp:72
Secant(const double epsilon, std::function< double(double)> f) noexcept
Definition Secant.hpp:58
Definition Bisection.hpp:43
std::uint32_t uint32
Definition Types.hpp:40