我如何在0和1之间迭代0.1步?
这表示step参数不能为零:
for i in range(0, 1, 0.1):
print(i)
我如何在0和1之间迭代0.1步?
这表示step参数不能为零:
for i in range(0, 1, 0.1):
print(i)
当前回答
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]
在'xrange([start], stop[, step])'基础上,你可以定义一个生成器,它接受并生成你选择的任何类型(坚持支持+和<的类型):
>>> def drange(start, stop, step):
... r = start
... while r < stop:
... yield r
... r += step
...
>>> i0=drange(0.0, 1.0, 0.1)
>>> ["%g" % x for x in i0]
['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']
>>>
可以使用Numpy库来完成。Arange()函数允许浮动中的步骤。但是,它返回一个numpy数组,为了方便起见,可以使用tolist()将其转换为列表。
for i in np.arange(0, 1, 0.1).tolist():
print i
这一行代码不会使代码变得混乱。step参数的符号很重要。
def frange(start, stop, step):
return [x*step+start for x in range(0,round(abs((stop-start)/step)+0.5001),
int((stop-start)/step<0)*-2+1)]
增加循环的i的大小,然后在需要时减少它。
for i * 100 in range(0, 100, 10):
print i / 100.0
编辑:老实说,我不记得为什么我认为这会在语法上工作
for i in range(0, 11, 1):
print i / 10.0
这应该有期望的输出。