To create the array you can use list
, by using a custom Floatrange
class, with the help of decimal
module:
from decimal import Decimal
class FloatRange:
def __init__(self, start, stop, step, include_right=False):
self.start = Decimal(f'{start}')
self.stop = Decimal(f'{stop}')
self.step = Decimal(f'{step}')
self.range = Decimal(f'{stop - start}')
self.include_right = include_right
self.len = len(self) + include_right
self.max_index = self.len - 1
self.count = 0
def __getitem__(self, index):
if index < 0:
index = self.len + index
if index > self.max_index:
raise IndexError('FloatRange index out of range.')
return float(self.start + index * self.step)
def __len__(self):
return int(self.range / self.step)
def __next__(self):
if self.count < self.len:
self.count += 1
return self[self.count-1]
if include_endpoint:
return stop
def __iter__(self):
while self.count < self.len:
yield next(self)
def to_numpy(self):
return np.fromiter(self)
def __repr__(self):
return (f"FloatRange("
f"start={self.start}, "
f"stop={self.stop}, "
f"step={self.step}, "
f"include_right={self.include_right})")
Then you can create a FloatRange
object:
>>> fr = FloatRange(xmin, xmax, spacing)
>>> fr
FloatRange(start=-377, stop=345, step=0.01, include_right=False)
>>> fr[-1]
344.99
>>> fr[38260]
5.6
>>> arr = fr.to_numpy() # Equivalent to: arr = np.array(list(fr))
>>> arr[38260]
5.6
If include_right==True
:
>>> fr = FloatRange(xmin, xmax, spacing, include_right=True)
>>> fr[-1]
345.0