我必须在这里定义我自己的 range() 浮点版本。它与内置 range() 函数的工作原理相同,但可以接受浮点值。start、stop 和 step 是整数或 float ,step 是非零值,也可以是负数。
我曾尝试在 stackoverflow 上寻找答案,但所有答案都只对积极的一步有效。我一直卡在测试值 (0,0.25,-1) 的测试中 我百分百确定有一个越来越快的方法来实现这个,因为我的程序需要很长时间来测试所有的值。有人可以帮我创建一个函数来执行此操作,但我无法使用导入的工具。
def float(start,stop,step):
x = start
my_list = []
if start < stop:
while x<stop:
my_list.append(x)
if x < 0:
x-=step
elif x > 0:
x+=step
else:
x+=step
return my_list
if start > stop:
while x<=start and x>stop:
my_list.append(x)
if x < 0:
x=step
elif x > 0:
x+=step
else:
x+=step
return my_list
请您参考如下方法:
将 float 步数转换为整数步数。由于 float 的舍入,您将减少错误漂移:
def float_range(start,stop,step):
istop = int((stop-start) // step)
for i in range(int(istop)):
yield start + i * step
