numerical-collection-cpp 0.10.0
A collection of algorithms in numerical analysis implemented in C++
Loading...
Searching...
No Matches
root.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
25#include "num_collect/constants/half.h" // IWYU pragma: keep
27#include "num_collect/constants/one.h" // IWYU pragma: keep
28#include "num_collect/constants/zero.h" // IWYU pragma: keep
29
30namespace num_collect::constants {
31
41template <typename F, typename I,
42 std::enable_if_t<std::is_floating_point_v<F> && std::is_integral_v<I>,
43 void*> = nullptr>
44constexpr auto root(F x, I n) -> F {
45 if (n < 2) {
46 return std::numeric_limits<F>::quiet_NaN();
47 }
48 if (x < zero<F>) {
49 if ((n % 2) == 0) {
50 return std::numeric_limits<F>::quiet_NaN();
51 }
52 return -root(-x, n);
53 }
54 if ((x > std::numeric_limits<F>::max()) ||
55 (x < std::numeric_limits<F>::min())) {
56 return x;
57 }
58
59 constexpr int max_loops = 1000; // safe guard
60 F value = one<F> + (x - one<F>) / static_cast<F>(n);
61 for (int i = 0; i < max_loops; ++i) {
62 F next_value = (static_cast<F>(n - one<I>) * value +
63 x * impl::pow_pos_int(one<I> / value, n - one<I>)) /
64 static_cast<F>(n);
65 if (value == next_value) {
66 break;
67 }
68 value = next_value;
69 }
70
71 return value;
72}
73
83template <typename IB, typename IE,
84 std::enable_if_t<std::is_integral_v<IB> && std::is_integral_v<IE>, void*> =
85 nullptr>
86constexpr auto root(IB x, IE n) -> double {
87 return root(static_cast<double>(x), n);
88}
89
90} // namespace num_collect::constants
Definition of half.
constexpr auto pow_pos_int(T base, I exp) -> T
Calculate the value of base raised to the power exp.
Definition pow_pos_int.h:40
Namespace of constexpr variables and functions.
Definition cbrt.h:24
constexpr T zero
Value 0.
Definition zero.h:30
constexpr auto root(F x, I n) -> F
Calculate n-th root .
Definition root.h:44
constexpr T one
Value 1.
Definition one.h:30
Definition of one.
Definition of pow_pos_int function.
Definition of zero.