numerical-collection-cpp 0.10.0
A collection of algorithms in numerical analysis implemented in C++
Loading...
Searching...
No Matches
sqrt.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
26#include "num_collect/constants/one.h" // IWYU pragma: keep
27#include "num_collect/constants/zero.h" // IWYU pragma: keep
28
29namespace num_collect::constants {
30
42template <typename F,
43 std::enable_if_t<std::is_floating_point_v<F>, void*> = nullptr>
44constexpr auto sqrt(F x) -> F {
45 if (x < zero<F>) {
46 return std::numeric_limits<F>::quiet_NaN();
47 }
48 if ((x > std::numeric_limits<F>::max()) ||
49 (x < std::numeric_limits<F>::min())) {
50 return x;
51 }
52
53 constexpr int max_loops = 1000; // safe guard
54 F value = half<F> * (x + one<F>);
55 for (int i = 0; i < max_loops; ++i) {
56 F next_value = half<F> * (value + x / value);
57 if (value == next_value) {
58 break;
59 }
60 value = next_value;
61 }
62
63 return value;
64}
65
77template <typename I, std::enable_if_t<std::is_integral_v<I>, void*> = nullptr>
78constexpr auto sqrt(I x) -> double {
79 return sqrt(static_cast<double>(x));
80}
81
82} // namespace num_collect::constants
Definition of half.
Namespace of constexpr variables and functions.
Definition cbrt.h:24
constexpr T zero
Value 0.
Definition zero.h:30
constexpr T half
Value 0.5.
Definition half.h:30
constexpr T one
Value 1.
Definition one.h:30
constexpr auto sqrt(F x) -> F
Calculate square root .
Definition sqrt.h:44
Definition of one.
Definition of zero.