Python 在整个时间间隔内迭代的聪明方法

Python 在整个时间间隔内迭代的聪明方法,python,Python,我使用此解决方案中的代码迭代小数点间隔: 但我有个问题。我的步长大约是0.001,而我的间隔是70.390829到70.855549。如何确保我实际上尽可能多地迭代间隔?我应该舍入到三位小数,以确保我得到尽可能多的面积吗?我的意思是,我需要尽可能接近开始,尽可能接近结束。那会有帮助吗?还有什么好主意吗?您可以使用numpy.linspace,它在给定的间隔内返回等距值,您只需给它三个参数,开始、停止和步数: numpy.linspace(70.390829, 70.855549, 464) 在

我使用此解决方案中的代码迭代小数点间隔:


但我有个问题。我的步长大约是0.001,而我的间隔是70.390829到70.855549。如何确保我实际上尽可能多地迭代间隔?我应该舍入到三位小数,以确保我得到尽可能多的面积吗?我的意思是,我需要尽可能接近开始,尽可能接近结束。那会有帮助吗?还有什么好主意吗?

您可以使用
numpy.linspace
,它在给定的间隔内返回等距值,您只需给它三个参数,开始、停止和步数:

numpy.linspace(70.390829, 70.855549, 464)

在此范围内使用464个样本将接近0.001的步长,但linspace将保证第一个和最后一个值将完全等于起始值和终止值,因此涵盖整个范围。

因为您似乎担心浮点数出现舍入错误,以下代码使用
decimal
模块允许您选择应用程序所需的精度:

>>> from decimal import Decimal as D
>>> compare = lambda a, b: (a > b) - (a < b)
>>> def drange(start, stop, step):
        relation = compare(stop, start)
        if not relation:
            raise ValueError('start and stop may not have the same value')
        if compare(relation, 0) != compare(step, 0):
            raise ValueError('step will not allow the sequence to finish')
        while True:
            yield start
            start += step
            if compare(stop, start) != relation:
                break

>>> sequence = tuple(drange(D('70.390829'), D('70.855549'), D('0.001')))
>>> len(sequence)
465

非常感谢。为了找到样本数,我想你找到了这两个值之间的差异,然后用我想要的步长除以它,然后再加上这个值或类似的东西?是的,这正是我得到步长数的方法,将会更新answer@bjornasm比那复杂一点。将距离乘以步长,然后将其添加到起始值。您可能需要添加一个小的模糊因子,以确保舍入不会导致
floor
丢失最后一个值。
>>> from decimal import Decimal as D
>>> compare = lambda a, b: (a > b) - (a < b)
>>> def drange(start, stop, step):
        relation = compare(stop, start)
        if not relation:
            raise ValueError('start and stop may not have the same value')
        if compare(relation, 0) != compare(step, 0):
            raise ValueError('step will not allow the sequence to finish')
        while True:
            yield start
            start += step
            if compare(stop, start) != relation:
                break

>>> sequence = tuple(drange(D('70.390829'), D('70.855549'), D('0.001')))
>>> len(sequence)
465
>>> sequence = tuple(drange(70.390829, 70.855549, 0.001))
>>> len(sequence)
465