Skip to content

Commit

Permalink
Switch from using Fraction to Decimal due to much better benchmarked …
Browse files Browse the repository at this point in the history
…speeds
  • Loading branch information
impredicative committed Feb 23, 2022
1 parent cd88a15 commit ac5ea74
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions wrapdisc/util/float.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""float utilities."""
from fractions import Fraction
from decimal import Decimal
from math import ceil, floor, inf, nextafter
from typing import Sequence, overload

Expand All @@ -9,7 +9,7 @@ def div_float(x: float, y: int | float, /) -> float:
Intermediate string representations are used.
"""
return float(Fraction(str(x)) / Fraction(str(y)))
return float(Decimal(str(x)) / Decimal(str(y)))


def sum_floats(nums: Sequence[int | float]) -> float:
Expand All @@ -18,7 +18,7 @@ def sum_floats(nums: Sequence[int | float]) -> float:
Intermediate string representations are used.
"""
# Note: math.fsum is not used because it was observed to not work well for the example [9.9, .05].
return float(sum(Fraction(str(f)) for f in nums))
return float(sum(Decimal(str(f)) for f in nums))


def next_float(val: float, /) -> float:
Expand Down Expand Up @@ -47,7 +47,7 @@ def round_nearest(num, to):
Intermediate string representations are used.
"""
# Ref: https://stackoverflow.com/a/70210770/
num, to = Fraction(str(num)), Fraction(str(to))
num, to = Decimal(str(num)), Decimal(str(to))
return float(round(num / to) * to)


Expand All @@ -57,7 +57,7 @@ def round_down(num: float, to: float) -> float:
Intermediate string representations are used.
"""
# Ref: https://stackoverflow.com/a/70210770/
num, to = Fraction(str(num)), Fraction(str(to))
num, to = Decimal(str(num)), Decimal(str(to))
return float(floor(num / to) * to)


Expand All @@ -67,5 +67,5 @@ def round_up(num: float, to: float) -> float:
Intermediate string representations are used.
"""
# Ref: https://stackoverflow.com/a/70210770/
num, to = Fraction(str(num)), Fraction(str(to))
num, to = Decimal(str(num)), Decimal(str(to))
return float(ceil(num / to) * to)

0 comments on commit ac5ea74

Please sign in to comment.