-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathhow_to_clamp_a_float.py
More file actions
81 lines (63 loc) · 2.32 KB
/
how_to_clamp_a_float.py
File metadata and controls
81 lines (63 loc) · 2.32 KB
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
78
79
80
81
"""
Tests the performance of all of the solutions listed in the following article:
https://therenegadecoder.com/code/how-to-clamp-a-floating-point-number-in-python/
"""
from test_bench import test_bench
def control(*_) -> None:
"""
Provides a control scenario for testing. In this case, none of the functions
share any overhead, so this function is empty.
:param _: a placeholder for the string input
:return: None
"""
pass
def clamp_float_with_branching_nested(num: float, minimum: float, maximum: float) -> float:
"""
Clamps a float between two bounds using a series of if statements.
:param num: the value to clamp
:param minimum: the lower bound
:param maximum: the upper bound
:return: a value in the range of minimum and maximum
"""
if num < minimum:
return minimum
elif num > maximum:
return maximum
else:
return num
def clamp_float_with_branching_flat(num: float, minimum: float, maximum: float) -> float:
"""
Clamps a float between two bounds using a series of ternary statements.
:param num: the value to clamp
:param minimum: the lower bound
:param maximum: the upper bound
:return: a value in the range of minimum and maximum
"""
return minimum if num < minimum else maximum if num > maximum else num
def clamp_float_with_min_and_max(num: float, minimum: float, maximum: float) -> float:
"""
Clamps a float between two bounds using a mix of min and max functions.
:param num: the value to clamp
:param minimum: the lower bound
:param maximum: the upper bound
:return: a value in the range of minimum and maximum
"""
return max(min(num, maximum), minimum)
def clamp_float_with_sorting(num: float, minimum: float, maximum: float) -> float:
"""
Clamps a float between two bounds using a sorting technique.
:param num: the value to clamp
:param minimum: the lower bound
:param maximum: the upper bound
:return: a value in the range of minimum and maximum
"""
sorted([num, minimum, maximum])[1]
if __name__ == "__main__":
test_bench(
{
"Lower Bound": [-.002, 0, .40],
"Upper Bound": [.402, 0, .40],
"Between Bounds": [.14, 0, .4],
"Large Numbers": [123456789, -432512317, 5487131463]
}
)