DryChem 1.0.0
A generic, compile-time C++ toolbox with no dependencies for the modern computational chemistry project.
Loading...
Searching...
No Matches
backwardsDifferenceMethod.hpp
Go to the documentation of this file.
1// Copyright (c) 2020-2025 Cody R. Drisko. All rights reserved.
2// Licensed under the MIT License. See the LICENSE file in the project root for more information.
3//
4// Name: backwardsDifferenceMethod.hpp
5// Author: crdrisko
6// Date: 11/13/2020-10:54:07
7// Description: Approximating the derivative of a function using the backwards difference method
8
9#ifndef DRYCHEM_COMMON_UTILITIES_INCLUDE_COMMON_UTILS_MATH_CALCULUS_DIFFERENTIATION_BACKWARDSDIFFERENCEMETHOD_HPP
10#define DRYCHEM_COMMON_UTILITIES_INCLUDE_COMMON_UTILS_MATH_CALCULUS_DIFFERENTIATION_BACKWARDSDIFFERENCEMETHOD_HPP
11
12#include <cstddef>
13#include <iterator>
14#include <type_traits>
15#include <vector>
16
18
20{
41 template<typename IteratorX, typename IteratorY = IteratorX,
42 typename Tx = typename std::iterator_traits<IteratorX>::value_type,
43 typename Ty = typename std::iterator_traits<IteratorY>::value_type,
44 typename = std::enable_if_t<std::conjunction_v<std::is_default_constructible<Tx>, std::is_default_constructible<Ty>>>>
45 constexpr auto backwardsDifferenceMethod(IteratorX x_begin, IteratorX x_end, IteratorY y_begin, IteratorY y_end)
46 {
47 using Ty_x = decltype(*y_begin / *x_begin);
48
49 std::ptrdiff_t x_size {x_end - x_begin}, y_size {y_end - y_begin};
50
51 if (x_size != y_size)
52 throw InputSizeMismatch {"Common-Utilities", __FILE__, __LINE__};
53
54 std::vector<Ty_x> dy_dx;
55
56 IteratorX x_iter {x_begin + 1};
57 IteratorY y_iter {y_begin + 1};
58
59 while (x_iter != x_end)
60 {
61 dy_dx.push_back((*y_iter - *(y_iter - 1)) / (*x_iter - *(x_iter - 1)));
62
63 ++x_iter;
64 ++y_iter;
65 }
66
67 return dy_dx;
68 }
69
73 template<typename ContainerX, typename ContainerY = ContainerX,
74 typename = std::enable_if_t<std::conjunction_v<std::is_default_constructible<typename ContainerX::value_type>,
75 std::is_default_constructible<typename ContainerY::value_type>>>>
76 constexpr auto backwardsDifferenceMethod(const ContainerX& x, const ContainerY& y)
77 {
78 return backwardsDifferenceMethod(x.begin(), x.end(), y.begin(), y.end());
79 }
80} // namespace CppUtils::Math
81
82#endif
Definition mathExceptions.hpp:25
Definition backwardsDifferenceMethod.hpp:20
constexpr auto backwardsDifferenceMethod(IteratorX x_begin, IteratorX x_end, IteratorY y_begin, IteratorY y_end)
Definition backwardsDifferenceMethod.hpp:45