Last active
January 17, 2023 01:31
-
-
Save adigitoleo/df3672cf1d17181fbae46477fb4d3825 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from fractions import Fraction | |
def fspread(count, start, end=None, step=None, mode=1): | |
"""Generate evenly-spaced floats. | |
Yields a sequence of evenly-spaced numbers. Optional `mode` controls | |
endpoint behaviour. Requires the stdlib class `fraction.Fraction`. Source: | |
http://code.activestate.com/recipes/577881-equally-spaced-floats-part-2/ | |
Parameters | |
---------- | |
count : int | |
Amount of subdivisions to be created. The actual amount of | |
numbers can be between ``count-1`` and ``count+1`` depending | |
on `mode`. | |
start : float | |
The starting value of the generator, included by default. | |
end : float, optional | |
The ending value of the generator, excluded by default. | |
step : float, optional | |
Size of the subdivisions to be created. A negative value results | |
in decreasing numbers. | |
mode : int, optional | |
Switch to control endpoint behaviour: | |
0 -> open interval, both `start` and `end` excluded | |
1 -> half-open, `start` included and `end` excluded (default) | |
2 -> half-open, `start` excluded and `end` included | |
3 -> closed interval, both `start` and `end` included | |
Examples | |
-------- | |
>>> list(fspread(5, 1.0, end=2.0)) | |
[1.0, 1.2, 1.4, 1.6, 1.8] | |
>>> list(fspread(5, 1.0, step=-0.25)) | |
[1.0, 0.75, 0.5, 0.25, 0.0] | |
""" | |
if end is step is None: | |
raise TypeError('one of end or step must be given') | |
if not isinstance(mode, int): | |
raise TypeError('mode must be an integer') | |
if count != int(count): | |
raise ValueError('count must be an integer') | |
if count <= 0: | |
raise ValueError('count must be positive') | |
if mode & 1: | |
yield start | |
if end is None: | |
step = Fraction(step) | |
end = start + count*step | |
else: | |
step = Fraction(end-start)/count | |
start = Fraction(start) | |
for i in range(1, count): | |
yield float(start + i*step) | |
if mode & 2: | |
yield float(end) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment