diff options
author | zaaarf <80046572+zaaarf@users.noreply.github.com> | 2024-01-02 15:48:56 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-01-02 15:48:56 +0100 |
commit | 791e64795a5f688e5ae673b88c5f2787d6450ce8 (patch) | |
tree | cf9324311fb1b49a09ccc17dc8f2ba4d24fae538 /src/openvic-simulation/utility | |
parent | 4c8da86c3bede8834f381fa63edaa3e140131f69 (diff) | |
parent | 2f5706fd5ef6bbdee54c82860e03f00a96751693 (diff) |
Merge pull request #114 from OpenVicProject/squared-roots
Integer and fixed point squared roots
Diffstat (limited to 'src/openvic-simulation/utility')
-rw-r--r-- | src/openvic-simulation/utility/NumberUtils.hpp | 29 |
1 files changed, 27 insertions, 2 deletions
diff --git a/src/openvic-simulation/utility/NumberUtils.hpp b/src/openvic-simulation/utility/NumberUtils.hpp index 6211772..d814019 100644 --- a/src/openvic-simulation/utility/NumberUtils.hpp +++ b/src/openvic-simulation/utility/NumberUtils.hpp @@ -9,7 +9,7 @@ namespace OpenVic::NumberUtils { return (num > 0.0) ? (num + 0.5) : (num - 0.5); } - constexpr uint64_t pow(uint64_t base, size_t exponent) { + constexpr uint64_t pow(uint64_t base, std::size_t exponent) { uint64_t ret = 1; while (exponent-- > 0) { ret *= base; @@ -17,11 +17,36 @@ namespace OpenVic::NumberUtils { return ret; } - constexpr int64_t pow(int64_t base, size_t exponent) { + constexpr int64_t pow(int64_t base, std::size_t exponent) { int64_t ret = 1; while (exponent-- > 0) { ret *= base; } return ret; } + + constexpr uint64_t sqrt(uint64_t n) { + uint64_t x = n; + uint64_t c = 0; + uint64_t d = 1ull << 62; + + while (d > n) + d >>= 2; + + for (; d != 0; d >>= 2) { + if (x >= c + d) { + x -= c + d; + c = (c >> 1) + d; + } else { + c >>= 1; + } + } + + //round up + if (x > 0) { + c += 1; + } + + return c; + } } |