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>
23
26
28
29namespace impl {
30
40template <typename Scalar>
41[[nodiscard]] inline auto process_one_arg_function(const variable<Scalar>& arg,
42 const Scalar& val, const Scalar& sensitivity) -> variable<Scalar> {
43 if (arg.node()) {
44 return variable<Scalar>(
45 val, graph::create_node<Scalar>(arg.node(), sensitivity));
46 }
47 return variable<Scalar>(val);
48}
49
50} // namespace impl
51
59template <typename Scalar>
60[[nodiscard]] inline auto exp(const variable<Scalar>& x) -> variable<Scalar> {
61 using std::exp;
62 const auto val = exp(x.value());
63 return impl::process_one_arg_function(x, val, val);
64}
65
73template <typename Scalar>
74[[nodiscard]] inline auto log(const variable<Scalar>& x) -> variable<Scalar> {
75 using std::log;
77 x, log(x.value()), static_cast<Scalar>(1) / x.value());
78}
79
87template <typename Scalar>
88[[nodiscard]] inline auto sqrt(const variable<Scalar>& x) -> variable<Scalar> {
89 using std::sqrt;
90 const auto val = sqrt(x.value());
91 const auto half = static_cast<Scalar>(0.5);
92 return impl::process_one_arg_function(x, val, half / val);
93}
94
95} // namespace num_collect::auto_diff::backward
Definition of node class.
Class of variables in backward-mode automatic differentiation kubota1998.
Definition variable.h:48
auto create_node(Args &&... args) -> node_ptr< Scalar >
Create a node.
Definition node.h:174
auto process_one_arg_function(const variable< Scalar > &arg, const Scalar &val, const Scalar &sensitivity) -> variable< Scalar >
Process a function with one argument.
Namespace of backward-mode automatic differentiation.
auto sqrt(const variable< Scalar > &x) -> variable< Scalar >
Calculate square root.
auto exp(const variable< Scalar > &x) -> variable< Scalar >
Calculate exponential.
auto log(const variable< Scalar > &x) -> variable< Scalar >
Calculate logarithm.
Definition of node class.