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)
39 return a;
40 }
41
42 // Find square root using binary search.
43 T lo = T(1);
44 T hi = T(a / 2 + 1);
45 T ans = T(0);
46
47 while (lo <= hi) {
48 T md = (lo + hi + 1) / 2;
49
50 if (md <= a / md) {
51 if (md * md == a) {
52 return md;
53 }
54 lo = md + 1;
55 ans = md;
56 } else {
57 hi = md - 1;
58 }
59 }
60
61 return ans;
62}
63
65MOCHI_WARNING_IGNORE_MSVC(4723) // warning C4723: potential divide by 0
66
67template <typename T>
68MOCHI_FORCE_INLINE constexpr T Sinc(T x) {
69 T x2 = x * x;
70 T x4 = x2 * x2;
71
72 if (x4 < std::numeric_limits<T>::epsilon())
74 return T(1) - x2 / T(6);
75 }
76 else {
77 return Sin(x) / x;
78 }
79}
80
82
83} // 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)