我如何在0和1之间迭代0.1步?

这表示step参数不能为零:

for i in range(0, 1, 0.1):
    print(i)

当前回答

f = lambda x,y,z: (x+i*z for i in range(int((y-x)/z)))

上面不需要借助任何库就可以做分数步。

其他回答

scipy有一个内置的函数arange,它泛化了Python的range()构造函数,以满足您对浮点数处理的需求。

从scipy进口安排

你可以使用这个函数:

def frange(start,end,step):
    return map(lambda x: x*step, range(int(start*1./step),int(end*1./step)))

Start和stop是包含的,而不是一个或另一个(通常不包括stop),并且没有导入,并使用生成器

def rangef(start, stop, step, fround=5):
    """
    Yields sequence of numbers from start (inclusive) to stop (inclusive)
    by step (increment) with rounding set to n digits.

    :param start: start of sequence
    :param stop: end of sequence
    :param step: int or float increment (e.g. 1 or 0.001)
    :param fround: float rounding, n decimal places
    :return:
    """
    try:
        i = 0
        while stop >= start and step > 0:
            if i==0:
                yield start
            elif start >= stop:
                yield stop
            elif start < stop:
                if start == 0:
                    yield 0
                if start != 0:
                    yield start
            i += 1
            start += step
            start = round(start, fround)
        else:
            pass
    except TypeError as e:
        yield "type-error({})".format(e)
    else:
        pass


# passing
print(list(rangef(-100.0,10.0,1)))
print(list(rangef(-100,0,0.5)))
print(list(rangef(-1,1,0.2)))
print(list(rangef(-1,1,0.1)))
print(list(rangef(-1,1,0.05)))
print(list(rangef(-1,1,0.02)))
print(list(rangef(-1,1,0.01)))
print(list(rangef(-1,1,0.005)))
# failing: type-error:
print(list(rangef("1","10","1")))
print(list(rangef(1,10,"1")))

Python 3.6.2 (v3.6.2:5fd33b5, july 8 2017, 04:57:36) [MSC v.1900 64 . 位(AMD64)]

最佳解决方案:没有舍入误差

>>> step = .1
>>> N = 10     # number of data points
>>> [ x / pow(step, -1) for x in range(0, N + 1) ]

[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

或者,对于一组范围而不是一组数据点(例如,连续函数),使用:

>>> step = .1
>>> rnge = 1     # NOTE range = 1, i.e. span of data points
>>> N = int(rnge / step
>>> [ x / pow(step,-1) for x in range(0, N + 1) ]

[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

实现一个函数:将x / pow(step, -1)替换为f(x / pow(step, -1)),并定义f。 例如:

>>> import math
>>> def f(x):
        return math.sin(x)

>>> step = .1
>>> rnge = 1     # NOTE range = 1, i.e. span of data points
>>> N = int(rnge / step)
>>> [ f( x / pow(step,-1) ) for x in range(0, N + 1) ]

[0.0, 0.09983341664682815, 0.19866933079506122, 0.29552020666133955, 0.3894183423086505, 
 0.479425538604203, 0.5646424733950354, 0.644217687237691, 0.7173560908995228,
 0.7833269096274834, 0.8414709848078965]

增加循环的i的大小,然后在需要时减少它。

for i * 100 in range(0, 100, 10):
    print i / 100.0

编辑:老实说,我不记得为什么我认为这会在语法上工作

for i in range(0, 11, 1):
    print i / 10.0

这应该有期望的输出。