numerical-collection-cpp 0.10.0
A collection of algorithms in numerical analysis implemented in C++
Loading...
Searching...
No Matches
variable_math.h
Go to the documentation of this file.
1/*
2 * Copyright 2021 MusicScience37 (Kenta Kabashima)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
20#pragma once
21
22#include <cmath> // IWYU pragma: keep
23
25
27
28namespace impl {
29
40template <typename Value, typename Diff>
41[[nodiscard]] inline auto process_one_arg_function(
42 const variable<Value, Diff>& arg, const Value& val,
43 const Value& sensitivity) -> variable<Value, Diff> {
44 if (arg.has_diff()) {
45 return variable<Value, Diff>(val, sensitivity * arg.diff());
46 }
47 return variable<Value, Diff>(val);
48}
49
50} // namespace impl
51
60template <typename Value, typename Diff>
61[[nodiscard]] inline auto exp(const variable<Value, Diff>& x)
63 using std::exp;
64 const auto val = exp(x.value());
65 return impl::process_one_arg_function(x, val, val);
66}
67
76template <typename Value, typename Diff>
77[[nodiscard]] inline auto log(const variable<Value, Diff>& x)
79 using std::log;
81 x, log(x.value()), static_cast<Value>(1) / x.value());
82}
83
92template <typename Value, typename Diff>
93[[nodiscard]] inline auto sqrt(const variable<Value, Diff>& x)
95 using std::sqrt;
96 const auto val = sqrt(x.value());
97 const auto half = static_cast<Value>(0.5);
98 return impl::process_one_arg_function(x, val, half / val);
99}
100
101} // namespace num_collect::auto_diff::forward
Class of variables in forward-mode automatic differentiation kubota1998.
Definition variable.h:43
Definition of variable class.
auto process_one_arg_function(const variable< Value, Diff > &arg, const Value &val, const Value &sensitivity) -> variable< Value, Diff >
Process a function with one argument.
Namespace of forward-mode automatic differentiation.
auto exp(const variable< Value, Diff > &x) -> variable< Value, Diff >
Calculate exponential.
auto log(const variable< Value, Diff > &x) -> variable< Value, Diff >
Calculate logarithm.
auto sqrt(const variable< Value, Diff > &x) -> variable< Value, Diff >
Calculate square root.