SuperDex Physics C++ API
Loading...
Searching...
No Matches
basic_utils_inl.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
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 */
16
17#pragma once
18
19#include "basic_utils.h"
20
21#include <limits>
22
23namespace superdex {
24
25template <typename T>
27 auto sqrt = Sqrt(Abs(a));
28 return Select(a >= T{}, sqrt, -sqrt);
29}
30
31template <typename T>
33 static_assert(
34 std::is_integral_v<T> && !std::is_same_v<std::remove_cv_t<T>, bool>, "Unsupported type");
35
36 // Base case.
37 if (a < 2) MOCHI_UNLIKELY {
38 return a;
39 }
40
41 // Find square root using binary search.
42 T lo = T(1);
43 T hi = T(a / 2 + 1);
44 T ans = T(0);
45
46 while (lo <= hi) {
47 T md = (lo + hi + 1) / 2;
48
49 if (md <= a / md) {
50 if (md * md == a) {
51 return md;
52 }
53 lo = md + 1;
54 ans = md;
55 } else {
56 hi = md - 1;
57 }
58 }
59
60 return ans;
61}
62
64MOCHI_WARNING_IGNORE_MSVC(4723) // warning C4723: potential divide by 0
65
66template <typename T>
67MOCHI_FORCE_INLINE constexpr T Sinc(T x) {
68 T x2 = x * x;
69 T x4 = x2 * x2;
70
71 if (x4 < std::numeric_limits<T>::epsilon()) MOCHI_UNLIKELY {
72 return T(1) - x2 / T(6);
73 } else {
74 return Sin(x) / x;
75 }
76}
77
79
80} // namespace superdex
#define MOCHI_UNLIKELY
#define MOCHI_WARNING_POP()
#define MOCHI_WARNING_IGNORE_MSVC(X)
#define MOCHI_WARNING_PUSH()
#define MOCHI_FORCE_INLINE
constexpr T Sin(T a)
constexpr T Abs(T a)
Definition basic_utils.h:50
constexpr T Select(bool condition, T a, T b)
constexpr T SignedSqrt(T a)
constexpr T Sqrt(T a)
constexpr T IntegralSqrt(T a)
constexpr T Sinc(T a)