Skip to content

Instantly share code, notes, and snippets.

@qexat
Last active May 13, 2024 18:08
Show Gist options
  • Save qexat/8b897e0b8cad6c337006de028f749d3f to your computer and use it in GitHub Desktop.
Save qexat/8b897e0b8cad6c337006de028f749d3f to your computer and use it in GitHub Desktop.
seems to fix float inaccuracies not too badly x)
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