numerical-collection-cpp 0.10.0
A collection of algorithms in numerical analysis implemented in C++
Loading...
Searching...
No Matches
log.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 <limits>
23#include <type_traits>
24
27#include "num_collect/constants/one.h" // IWYU pragma: keep
28
29namespace num_collect::constants {
30
42template <typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
43constexpr auto log(T x) -> T {
44 if (x < zero<T>) {
45 return std::numeric_limits<T>::quiet_NaN();
46 }
47 if (x == zero<T>) {
48 return -std::numeric_limits<T>::infinity();
49 }
50
51 if (x > one<T>) {
52 return -log(one<T> / x);
53 }
54
55 T value = impl::log1m_maclaurin(one<T> - x);
56 constexpr int max_loops = 1000;
57 for (int i = 0; i < max_loops; ++i) {
58 T exp_val = exp(value);
59 T next_value = value - (exp_val - x) / exp_val;
60 if (value == next_value) {
61 break;
62 }
63 value = next_value;
64 }
65
66 return value;
67}
68
69} // namespace num_collect::constants
Definition of exp function.
Definition of log1m_maclaurin function.
constexpr auto log1m_maclaurin(T x) -> T
Calculate logarithm of 1 - x.
Namespace of constexpr variables and functions.
Definition cbrt.h:24
constexpr auto exp(T x) -> T
Calculate exponential function .
Definition exp.h:46
constexpr T zero
Value 0.
Definition zero.h:30
constexpr auto log(T x) -> T
Calculate logarithm .
Definition log.h:43
constexpr T one
Value 1.
Definition one.h:30
Definition of one.