Eva*_*ark 679 python floating-point range
有没有办法介于0和1之间0.1?
我以为我可以像下面这样做,但它失败了:
for i in range(0, 1, 0.1):
print i
Run Code Online (Sandbox Code Playgroud)
相反,它说步骤参数不能为零,这是我没想到的.
And*_*ffe 818
而不是直接使用小数步骤,根据您想要的点数来表达它更安全.否则,浮点舍入错误可能会给您一个错误的结果.
您可以使用linspace
从功能与NumPy库(这不是标准库的一部分,但也比较容易获得).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])
Run Code Online (Sandbox Code Playgroud)
如果你真的想使用浮点步长值,你可以使用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])
Run Code Online (Sandbox Code Playgroud)
但是,浮点舍入错误会导致问题.这是一个简单的情况,当舍入错误导致arange
生成长度为4的数组时它应该只生成3个数字:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
Run Code Online (Sandbox Code Playgroud)
小智 199
Python的range()只能做整数,而不是浮点数.在您的特定情况下,您可以使用列表理解:
[x * 0.1 for x in range(0, 10)]
Run Code Online (Sandbox Code Playgroud)
(将调用替换为该表达式的范围.)
对于更一般的情况,您可能想要编写自定义函数或生成器.
gim*_*mel 146
在'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']
>>>
Run Code Online (Sandbox Code Playgroud)
cms*_*sjr 31
增加i
循环的幅度,然后在需要时减少它.
for i * 100 in range(0, 100, 10):
print i / 100.0
Run Code Online (Sandbox Code Playgroud)
编辑:老实说,我不记得为什么我认为这会在语法上有效
for i in range(0, 11, 1):
print i / 10.0
Run Code Online (Sandbox Code Playgroud)
那应该有所需的输出.
小智 23
scipy
有一个内置函数arange
,它泛化了Python的range()
构造函数,以满足您对浮点处理的要求.
from scipy import arange
Kal*_*lle 23
我认为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]
Run Code Online (Sandbox Code Playgroud)
一般来说,做逐步的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]
Run Code Online (Sandbox Code Playgroud)
(1/x
测试时产生的圆角噪声较小).
zef*_*ino 16
与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([])
Run Code Online (Sandbox Code Playgroud)
seq(1, 5, 0.5)
Run Code Online (Sandbox Code Playgroud)
[1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0]
seq(10, 0, -1)
Run Code Online (Sandbox Code Playgroud)
[10,9,8,7,6,5,4,3,2,1,0]
seq(10, 0, -2)
Run Code Online (Sandbox Code Playgroud)
[10,8,6,4,2,0]
seq(1, 1)
Run Code Online (Sandbox Code Playgroud)
[1]
Dan*_*ana 12
range()内置函数返回一个整数值序列,我担心,所以你不能用它来做一个小数步.
我只想使用while循环:
i = 0.0
while i <= 1.0:
print i
i += 0.1
Run Code Online (Sandbox Code Playgroud)
如果你很好奇,Python会将你的0.1转换为0,这就是为什么它告诉你参数不能为零.
Pra*_*mod 12
这是使用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)
Run Code Online (Sandbox Code Playgroud)
用法示例:
for i in seq(0, 1, 0.1):
print(i)
Run Code Online (Sandbox Code Playgroud)
小智 9
[x * 0.1 for x in range(0, 10)]
Run Code Online (Sandbox Code Playgroud)
在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)]
Run Code Online (Sandbox Code Playgroud)
给你想要的:
[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
小智 9
import numpy as np
for i in np.arange(0, 1, 0.1):
print i
Run Code Online (Sandbox Code Playgroud)
more_itertools
是一个实现numeric_range
工具的第三方库:
import more_itertools as mit
for x in mit.numeric_range(0, 1, 0.1):
print("{:.1f}".format(x))
Run Code Online (Sandbox Code Playgroud)
输出
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
Run Code Online (Sandbox Code Playgroud)
如果经常这样做,您可能希望保存生成的列表 r
r=map(lambda x: x/10.0,range(0,10))
for i in r:
print i
Run Code Online (Sandbox Code Playgroud)
我的版本使用原始范围函数来为移位创建乘法索引。这允许与原始范围函数相同的语法。我制作了两个版本,一种使用 float,一种使用 Decimal,因为我发现在某些情况下我想避免浮点运算引入的舍入漂移。
它与 range/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)) # []
Run Code Online (Sandbox Code Playgroud)
最佳解决方案:没有舍入错误
>>> 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]
Run Code Online (Sandbox Code Playgroud)
或者,对于设定范围而不是设定数据点(例如连续函数),使用:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
实现一个功能:替换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]
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是,还没有人在 Python 3 文档中提到推荐的解决方案:
也可以看看:
- linspace配方展示了如何实现适合浮点应用程序的范围的惰性版本。
一旦定义,配方就很容易使用,不需要numpy
或任何其他外部库,但功能类似于numpy.linspace()
. step
请注意,第三个参数不是参数,num
而是指定所需值的数量,例如:
print(linspace(0, 10, 5))
# linspace(0, 10, 5)
print(list(linspace(0, 10, 5)))
# [0.0, 2.5, 5.0, 7.5, 10]
Run Code Online (Sandbox Code Playgroud)
下面我引用了 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))
Run Code Online (Sandbox Code Playgroud)
这里的许多解决方案在 Python 3.6 中仍然存在浮点错误,并且没有完全满足我个人的需要。
下面的函数接受整数或浮点数,不需要导入并且不返回浮点错误。
def frange(x, y, step):
if int(x + y + step) == (x + y + step):
r = list(range(int(x), int(y), int(step)))
else:
f = 10 ** (len(str(step)) - str(step).find('.') - 1)
rf = list(range(int(x * f), int(y * f), int(step * f)))
r = [i / f for i in rf]
return r
Run Code Online (Sandbox Code Playgroud)