有没有办法在0和1之间以0.1步进?
我以为我可以像下面那样做,但是失败了:
for i in range(0, 1, 0.1):
print i
相反,它说step参数不能为零,这是我没有想到的。
#1楼
[x * 0.1 for x in range(0, 10)]
在Python 2.7x中,结果如下:
[0.0、0.1、0.2、0.30000000000000004、0.4、0.5、0.6000000000000001、0.7000000000000001、0.8、0.9]
但如果您使用:
[ round(x * 0.1, 1) for x in range(0, 10)]
给您所需的:
[0.0、0.1、0.2、0.3、0.4、0.5、0.6、0.7、0.8、0.9]
#2楼
与R的 seq
函数类似,此函数以正确的步长值以任意顺序返回序列。 最后一个值等于停止值。
def seq(start, stop, step=1):
n = int(round((stop - start)/float(step)))
if n > 1:
return([start + step*i for i in range(n+1)])
elif n == 1:
return([start])
else:
return([])
结果
seq(1, 5, 0.5)
[1.0、1.5、2.0、2.5、3.0、3.5、4.0、4.5、5.0]
seq(10, 0, -1)
[10、9、8、7、6、5、4、3、2、1、0]
seq(10, 0, -2)
[10、8、6、4、2、0]
seq(1, 1)
[1]
#3楼
我的解决方案:
def seq(start, stop, step=1, digit=0):
x = float(start)
v = []
while x <= stop:
v.append(round(x,digit))
x += step
return v
#4楼
import numpy as np
for i in np.arange(0, 1, 0.1):
print i
#5楼
这是使用itertools的解决方案:
import itertools
def seq(start, end, step):
if step == 0:
raise ValueError("step must not be 0")
sample_count = int(abs(end - start) / step)
return itertools.islice(itertools.count(start, step), sample_count)
用法示例:
for i in seq(0, 1, 0.1):
print(i)
#6楼
我的版本使用原始的范围函数来为班次创建乘法索引。 这允许与原始范围函数使用相同的语法。 我做了两个版本,一个使用浮点,一个使用十进制,因为我发现在某些情况下我想避免浮点算术引入的舍入漂移。
它与范围/ xrange中的空集结果一致。
仅将单个数值传递给任何一个函数都将使标准范围输出返回到输入参数的整数上限值(因此,如果给定5.5,则它将返回range(6)。)
编辑:下面的代码现在可以在pypi上作为软件包使用: Franges
## frange.py
from math import ceil
# find best range function available to version (2.7.x / 3.x.x)
try:
_xrange = xrange
except NameError:
_xrange = range
def frange(start, stop = None, step = 1):
"""frange generates a set of floating point values over the
range [start, stop) with step size step
frange([start,] stop [, step ])"""
if stop is None:
for x in _xrange(int(ceil(start))):
yield x
else:
# create a generator expression for the index values
indices = (i for i in _xrange(0, int((stop-start)/step)))
# yield results
for i in indices:
yield start + step*i
## drange.py
import decimal
from math import ceil
# find best range function available to version (2.7.x / 3.x.x)
try:
_xrange = xrange
except NameError:
_xrange = range
def drange(start, stop = None, step = 1, precision = None):
"""drange generates a set of Decimal values over the
range [start, stop) with step size step
drange([start,] stop, [step [,precision]])"""
if stop is None:
for x in _xrange(int(ceil(start))):
yield x
else:
# find precision
if precision is not None:
decimal.getcontext().prec = precision
# convert values to decimals
start = decimal.Decimal(start)
stop = decimal.Decimal(stop)
step = decimal.Decimal(step)
# create a generator expression for the index values
indices = (
i for i in _xrange(
0,
((stop-start)/step).to_integral_value()
)
)
# yield results
for i in indices:
yield float(start + step*i)
## testranges.py
import frange
import drange
list(frange.frange(0, 2, 0.5)) # [0.0, 0.5, 1.0, 1.5]
list(drange.drange(0, 2, 0.5, precision = 6)) # [0.0, 0.5, 1.0, 1.5]
list(frange.frange(3)) # [0, 1, 2]
list(frange.frange(3.5)) # [0, 1, 2, 3]
list(frange.frange(0,10, -1)) # []
#7楼
这是我的解决方案,它与float_range(-1,0,0.01)一起正常工作,并且没有浮点表示错误。 它不是很快,但是可以正常工作:
from decimal import Decimal
def get_multiplier(_from, _to, step):
digits = []
for number in [_from, _to, step]:
pre = Decimal(str(number)) % 1
digit = len(str(pre)) - 2
digits.append(digit)
max_digits = max(digits)
return float(10 ** (max_digits))
def float_range(_from, _to, step, include=False):
"""Generates a range list of floating point values over the Range [start, stop]
with step size step
include=True - allows to include right value to if possible
!! Works fine with floating point representation !!
"""
mult = get_multiplier(_from, _to, step)
# print mult
int_from = int(round(_from * mult))
int_to = int(round(_to * mult))
int_step = int(round(step * mult))
# print int_from,int_to,int_step
if include:
result = range(int_from, int_to + int_step, int_step)
result = [r for r in result if r <= int_to]
else:
result = range(int_from, int_to, int_step)
# print result
float_result = [r / mult for r in result]
return float_result
print float_range(-1, 0, 0.01,include=False)
assert float_range(1.01, 2.06, 5.05 % 1, True) ==\
[1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01, 2.06]
assert float_range(1.01, 2.06, 5.05 % 1, False)==\
[1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01]
#8楼
我只是一个初学者,但是在模拟某些计算时遇到了同样的问题。 这是我尝试解决的方法,似乎正在使用小数步。
我也很懒,所以我发现很难编写自己的范围函数。
基本上,我所做的是将xrange(0.0, 1.0, 0.01)
xrange(0, 100, 1)
xrange(0.0, 1.0, 0.01)
更改为xrange(0, 100, 1)
并在循环内使用了100.0
除法。 我也很担心是否会出现四舍五入的错误。 所以我决定测试是否有。 现在我听说,如果例如0.01
从计算是不完全的浮动0.01
比较它们应该返回False(如果我错了,请让我知道)。
因此,我决定通过运行简短的测试来测试我的解决方案是否适合我的范围:
for d100 in xrange(0, 100, 1):
d = d100 / 100.0
fl = float("0.00"[:4 - len(str(d100))] + str(d100))
print d, "=", fl , d == fl
并且每个都打印True。
现在,如果我完全错了,请告诉我。
#9楼
这个衬里不会使您的代码混乱。 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)]
#10楼
这是我使用浮动步长获取范围的解决方案。
使用此功能,无需导入numpy或安装它。
我很确定可以对其进行改进和优化。 随意做并张贴在这里。
from __future__ import division
from math import log
def xfrange(start, stop, step):
old_start = start #backup this value
digits = int(round(log(10000, 10)))+1 #get number of digits
magnitude = 10**digits
stop = int(magnitude * stop) #convert from
step = int(magnitude * step) #0.1 to 10 (e.g.)
if start == 0:
start = 10**(digits-1)
else:
start = 10**(digits)*start
data = [] #create array
#calc number of iterations
end_loop = int((stop-start)//step)
if old_start == 0:
end_loop += 1
acc = start
for i in xrange(0, end_loop):
data.append(acc/magnitude)
acc += step
return data
print xfrange(1, 2.1, 0.1)
print xfrange(0, 1.1, 0.1)
print xfrange(-1, 0.1, 0.1)
输出为:
[1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1]
[-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0]
#11楼
scipy
有一个内置的功能, arange
推广了Python的range()
构造函数,以满足您的浮动处理要求。
from scipy import arange
#12楼
范围(开始,停止,精度)
def frange(a,b,i):
p = 10**i
sr = a*p
er = (b*p) + 1
p = float(p)
return map(lambda x: x/p, xrange(sr,er))
In >frange(-1,1,1)
Out>[-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
#13楼
您可以使用此功能:
def frange(start,end,step):
return map(lambda x: x*step, range(int(start*1./step),int(end*1./step)))
#14楼
诀窍避免四舍五入问题是使用一个单独的号码通过的范围内移动,启动和启动的领先一步 的一半 。
# 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
。
#15楼
为了完善精品店,提供了一个实用的解决方案:
def frange(a,b,s):
return [] if s > 0 and a > b or s < 0 and a < b or s==0 else [a]+frange(a+s,b,s)
#16楼
可以使用Numpy库完成。 arange()函数允许进行浮动操作。 但是,它返回一个numpy数组,为方便起见,可以使用tolist()将其转换为list。
for i in np.arange(0, 1, 0.1).tolist():
print i
#17楼
最佳解决方案: 无舍入错误
_________________________________________________________________________________
>>> 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]
要实现一个功能:用f( x / pow(step, -1) )
替换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]
#18楼
我的答案与使用map()的其他答案类似,不需要NumPy,也不需要使用lambda(尽管可以)。 要以dt的步长获取从0.0到t_max的浮点值列表:
def xdt(n):
return dt*float(n)
tlist = map(xdt, range(int(t_max/dt)+1))
#19楼
我认为NumPy有点矫kill过正。
[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]
一般来说,要逐步进行y
1/x
运算,
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
产生的舍入噪声较小)。
#20楼
添加自动更正,以防止出现错误的登录步骤:
def frange(start,step,stop):
step *= 2*((stop>start)^(step<0))-1
return [start+i*step for i in range(int((stop-start)/step))]
#21楼
为循环增加i
的大小,然后在需要时减小i
的大小。
for i * 100 in range(0, 100, 10):
print i / 100.0
编辑:老实说,我不记得为什么我认为这将在语法上起作用
for i in range(0, 11, 1):
print i / 10.0
那应该具有所需的输出。
#22楼
恐怕range()内置函数会返回一个整数值序列,因此您不能使用它执行小数步。
我想说的只是使用while循环:
i = 0.0
while i <= 1.0:
print i
i += 0.1
如果您很好奇,Python会将您的0.1转换为0,这就是为什么它告诉您参数不能为零的原因。
#23楼
Python的range()只能做整数,不能做浮点数。 在您的特定情况下,可以改用列表推导:
[x * 0.1 for x in range(0, 10)]
(用该表达式将调用替换为range。)
对于更一般的情况,您可能需要编写自定义函数或生成器。
#24楼
如果你这样做的时候,你可能想保存生成的列表r
r=map(lambda x: x/10.0,range(0,10))
for i in r:
print i
#25楼
在'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']
>>>
#26楼
与直接使用小数步相比,用所需的点数表示这一点要安全得多。 否则,浮点舍入错误可能会给您带来错误的结果。
您可以使用NumPy库中的linspace
函数(该库不是标准库的一部分,但相对容易获得)。 linspace
需要返回多个点,还可以指定是否包括正确的端点:
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
如果您确实要使用浮点步进值,则可以使用numpy.arange
。
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
但是,浮点舍入错误会引起问题。 这是一个简单的情况,当四舍五入误差仅会产生3个数字时,会导致arange
产生一个length-4数组:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
#27楼
more_itertools
是一个第三方库,它实现了numeric_range
工具:
import more_itertools as mit
for x in mit.numeric_range(0, 1, 0.1):
print("{:.1f}".format(x))
输出量
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
#28楼
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,2017年7月8日,04:57:36)[MSC v.1900 64位(AMD64)]
#29楼
令人惊讶的是,没有人在Python 3文档中提到推荐的解决方案:
也可以看看:
- linspace配方显示了如何实现适用于浮点应用程序的lazy版本的range。
定义后,该食谱易于使用,不需要numpy
或任何其他外部库,但可以使用numpy.linspace()
类的功能。 请注意,第三个num
参数指定了所需值的数量,而不是step
参数,例如:
print(linspace(0, 10, 5))
# linspace(0, 10, 5)
print(list(linspace(0, 10, 5)))
# [0.0, 2.5, 5.0, 7.5, 10]
我在下面引用了来自Andrew Barnert的完整Python 3配方的修改版本:
import collections.abc
import numbers
class linspace(collections.abc.Sequence):
"""linspace(start, stop, num) -> linspace object
Return a virtual sequence of num numbers from start to stop (inclusive).
If you need a half-open range, use linspace(start, stop, num+1)[:-1].
"""
def __init__(self, start, stop, num):
if not isinstance(num, numbers.Integral) or num <= 1:
raise ValueError('num must be an integer > 1')
self.start, self.stop, self.num = start, stop, num
self.step = (stop-start)/(num-1)
def __len__(self):
return self.num
def __getitem__(self, i):
if isinstance(i, slice):
return [self[x] for x in range(*i.indices(len(self)))]
if i < 0:
i = self.num + i
if i >= self.num:
raise IndexError('linspace object index out of range')
if i == self.num-1:
return self.stop
return self.start + i*self.step
def __repr__(self):
return '{}({}, {}, {})'.format(type(self).__name__,
self.start, self.stop, self.num)
def __eq__(self, other):
if not isinstance(other, linspace):
return False
return ((self.start, self.stop, self.num) ==
(other.start, other.stop, other.num))
def __ne__(self, other):
return not self==other
def __hash__(self):
return hash((type(self), self.start, self.stop, self.num))
#30楼
要解决浮点精度问题,可以使用Decimal
模块 。
这需要在编写代码时从int
或float
转换为Decimal
的额外工作,但是如果确实需要这种便利,则可以传递str
并修改函数。
from decimal import Decimal
from decimal import Decimal as D
def decimal_range(*args):
zero, one = Decimal('0'), Decimal('1')
if len(args) == 1:
start, stop, step = zero, args[0], one
elif len(args) == 2:
start, stop, step = args + (one,)
elif len(args) == 3:
start, stop, step = args
else:
raise ValueError('Expected 1 or 2 arguments, got %s' % len(args))
if not all([type(arg) == Decimal for arg in (start, stop, step)]):
raise ValueError('Arguments must be passed as <type: Decimal>')
# neglect bad cases
if (start == stop) or (start > stop and step >= zero) or \
(start < stop and step <= zero):
return []
current = start
while abs(current) < abs(stop):
yield current
current += step
样本输出-
list(decimal_range(D('2')))
# [Decimal('0'), Decimal('1')]
list(decimal_range(D('2'), D('4.5')))
# [Decimal('2'), Decimal('3'), Decimal('4')]
list(decimal_range(D('2'), D('4.5'), D('0.5')))
# [Decimal('2'), Decimal('2.5'), Decimal('3.0'), Decimal('3.5'), Decimal('4.0')]
list(decimal_range(D('2'), D('4.5'), D('-0.5')))
# []
list(decimal_range(D('2'), D('-4.5'), D('-0.5')))
# [Decimal('2'),
# Decimal('1.5'),
# Decimal('1.0'),
# Decimal('0.5'),
# Decimal('0.0'),
# Decimal('-0.5'),
# Decimal('-1.0'),
# Decimal('-1.5'),
# Decimal('-2.0'),
# Decimal('-2.5'),
# Decimal('-3.0'),
# Decimal('-3.5'),
# Decimal('-4.0')]