我如何在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)
当前回答
你可以使用这个函数:
def frange(start,end,step):
return map(lambda x: x*step, range(int(start*1./step),int(end*1./step)))
其他回答
在步骤中添加可能出现错误符号的自动更正:
def frange(start,step,stop):
step *= 2*((stop>start)^(step<0))-1
return [start+i*step for i in range(int((stop-start)/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)]
import numpy as np
for i in np.arange(0, 1, 0.1):
print i
避免四舍五入问题的技巧是使用一个单独的数字在范围内移动,该数字在开始前半步开始。
# floating point range
def frange(a, b, stp=1.0):
i = a+stp/2.0
while i<b:
yield a
a += stp
i += stp
另外,numpy。可以使用Arange。
我认为NumPy有点过头了。
[p/10 for p in range(0, 10)]
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
一般来说,要做阶跃1/x直到y
x=100
y=2
[p/x for p in range(0, int(x*y))]
[0.0, 0.01, 0.02, 0.03, ..., 1.97, 1.98, 1.99]
(1/x在我测试时产生的舍入噪声更少)。