numerical-collection-cpp 0.10.0
A collection of algorithms in numerical analysis implemented in C++
Loading...
Searching...
No Matches
log1p.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
28#include "num_collect/constants/one.h" // IWYU pragma: keep
29
30namespace num_collect::constants {
31
46template <typename T, typename = std::enable_if_t<std::is_floating_point_v<T>>>
47constexpr auto log1p(T x) -> T {
48 if (x < -one<T>) {
49 return std::numeric_limits<T>::quiet_NaN();
50 }
51 if (x == -one<T>) {
52 return -std::numeric_limits<T>::infinity();
53 }
54
55 if (x > one<T>) {
56 return log(x + one<T>);
57 }
58 if (x > zero<T>) {
59 return -log1p(-x / (x + one<T>));
60 }
61
62 T value = x;
63 if (x > zero<T>) {
64 value = -log1p(-x / (x + one<T>));
65 } else {
66 value = impl::log1m_maclaurin(-x);
67 }
68 constexpr int max_loops = 1000;
69 for (int i = 0; i < max_loops; ++i) {
70 T expm1_val = expm1(value);
71 T next_value = value - (expm1_val - x) / (expm1_val + one<T>);
72 if (value == next_value) {
73 break;
74 }
75 value = next_value;
76 }
77
78 return value;
79}
80
81} // namespace num_collect::constants
Definition of exp function.
Definition of log1m_maclaurin function.
Definition of log function.
constexpr auto log1m_maclaurin(T x) -> T
Calculate logarithm of 1 - x.
Namespace of constexpr variables and functions.
Definition cbrt.h:24
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
constexpr auto expm1(T x) -> T
Calculate exponential function minus one .
Definition expm1.h:49
constexpr auto log1p(T x) -> T
Calculate natural logarithm of 1 + x, .
Definition log1p.h:47
Definition of one.