blob: f59700da88f914311f39b1b3d72708c901bc306f (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
#pragma once
#include <util/system/types.h>
#include <cmath>
#include <optional>
#include <fenv.h>
namespace NMathUdf {
template <class T>
inline T RoundToDecimal(T v, int decShift) {
T div = std::pow(T(10), decShift);
return std::floor(v / div + T(0.5)) * div;
}
inline std::optional<i64> Mod(i64 value, i64 m) {
if (!m) {
return {};
}
const i64 result = value % m;
if ((result < 0 && m > 0) || (result > 0 && m < 0)) {
return result + m;
}
return result;
}
inline std::optional<i64> Rem(i64 value, i64 m) {
if (!m) {
return {};
}
const i64 result = value % m;
if (result < 0 && value > 0) {
return result + m;
}
if (result > 0 && value < 0) {
return result - m;
}
return result;
}
inline std::optional<i64> NearbyIntImpl(double value, decltype(FE_DOWNWARD) mode) {
if (!::isfinite(value)) {
return {};
}
auto prevMode = ::fegetround();
::fesetround(mode);
auto res = ::nearbyint(value);
::fesetround(prevMode);
// cast to i64 gives wrong sign above 9223372036854774784
// lower bound is adjusted to -9223372036854774784 as well
if (res < double(std::numeric_limits<i64>::min() + 513) || res > double(std::numeric_limits<i64>::max() - 512)) {
return {};
}
return static_cast<i64>(res);
}
inline std::optional<i64> NearbyInt(double value, ui32 mode) {
switch (mode) {
case 0:
return NearbyIntImpl(value, FE_DOWNWARD);
case 1:
return NearbyIntImpl(value, FE_TONEAREST);
case 2:
return NearbyIntImpl(value, FE_TOWARDZERO);
case 3:
return NearbyIntImpl(value, FE_UPWARD);
default:
return {};
}
}
}
|