Last active
May 13, 2024 18:08
-
-
Save qexat/8b897e0b8cad6c337006de028f749d3f to your computer and use it in GitHub Desktop.
seems to fix float inaccuracies not too badly x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import sys | |
CORRECTOR = ((4 - sys.float_info.max * sys.float_info.min) / 2.5) | |
def fix_float(value: float) -> float: | |
if abs(value) < sys.float_info.epsilon: | |
return 0.0 | |
corrector = math.copysign(CORRECTOR, value) | |
epsilon = math.copysign(sys.float_info.epsilon, value) | |
return value - epsilon + corrector | |
def main() -> None: | |
x = 0.1 + 0.2 | |
fixed_x = fix_float(x) | |
print(x, fixed_x) | |
y = 0.2 + 0.4 | |
fixed_y = fix_float(y) | |
print(y, fixed_y) | |
# let's try with a result without approximation issues | |
z = 1.2 + 3.5 | |
fixed_z = fix_float(z) | |
print(z, fixed_z) # still correct | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment