Apr-27-2019, 07:49 PM
Hi
I need to add range of numbers to some arrays used, but I see that range in Python is not for float numbers and is not inclusive, namely range is not including the last number.
Seems that we need to use extra functions to complement the default function in Python.
I was able to get ranges using floats using this function:
Thank you very much for your reply
Mapg
I need to add range of numbers to some arrays used, but I see that range in Python is not for float numbers and is not inclusive, namely range is not including the last number.
Seems that we need to use extra functions to complement the default function in Python.
I was able to get ranges using floats using this function:
def float_range(start, stop, skip = 1.0, decimals = 2): for i in range(int(start / skip), int(stop / skip)): yield float(('%0.' + str(decimals) + 'f') % (i * skip)) my_float_range = float_range(0.45, 0.6, 0.01) all_combo = list(my_float_range) print(f'size={len(all_combo)}') pprint(all_combo)
Output:size=15 [0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59]
BUT I need to get in the array 0.60 too!!
I have this function to get inclusive ranges, but is not valid for float numbersdef closed_range(slices): slice_parts = slices.split(',') [start, stop, step] = map(int, slice_parts) num = start if start <= stop and step > 0: while num <= stop: yield num num += step # if negative step elif step < 0: while num >= stop: yield num num += step all_combo = list(closed_range('1, 6, 1')) print(f'size={len(all_combo)}') pprint(all_combo)
Output: size=6 [1, 2, 3, 4, 5, 6]
How can I get inclusive ranges also valid for float numbers?Thank you very much for your reply
Mapg