Skip to content

Instantly share code, notes, and snippets.

@JoaoRodrigues
Last active October 6, 2020 23:13
Show Gist options
  • Save JoaoRodrigues/f23698bf1ebe1f307792195943eebb90 to your computer and use it in GitHub Desktop.
Save JoaoRodrigues/f23698bf1ebe1f307792195943eebb90 to your computer and use it in GitHub Desktop.
Python 3.x range-like function with decimal step
import decimal
def frange(start, stop, step, include_stop=True):
"""Range-like function that accepts decimal step values."""
# To avoid rounding issues
# We cast the floats to string and then to decimals
# see: docs on Decimal(0.1) != Decimal('0.1')
dstep = decimal.Decimal(str(step))
# We round the boundaries to the precision of the step
# to avoid further issues with limits.
precision = -1 * dstep.as_tuple().exponent
val = decimal.Decimal(f"{start:.{precision}f}")
end = decimal.Decimal(f"{stop:.{precision}f}")
# Define stopping condition
if include_stop:
check = lambda v: v <= end
else:
check = lambda v: v < end
n = 0 # number of cycles
while check(val):
yield start + n*step # return the "full precision" value
val += dstep # to keep the boundary condition
n += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment