How to use a decimal range() step value?
有没有办法用0.1在0和1之间切换?
我原以为我可以这样做,但失败了:
1 2 | for i in range(0, 1, 0.1): print i |
相反,它说步骤参数不能为零,这是我没有预料到的。
与其直接使用小数步,不如用你想要的点数来表示它更安全。否则,浮点舍入错误可能会给出错误的结果。
您可以使用numpy库中的
1 2 3 4 | >>> 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]) |
如果您真的想使用浮点阶跃值,可以使用
1 2 3 | >>> 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]) |
不过,浮点舍入错误会导致问题。这里有一个简单的例子,舍入误差导致
1 2 | >>> numpy.arange(1, 1.3, 0.1) array([1. , 1.1, 1.2, 1.3]) |
python的range()只能执行整数,不能执行浮点运算。在您的特定情况下,您可以使用列表理解代替:
1 | [x * 0.1 for x in range(0, 10)] |
(用该表达式替换对范围的调用。)
对于更一般的情况,您可能需要编写自定义函数或生成器。
基于'xrange([start],stop[,step]),您可以定义一个接受并生成您选择的任何类型的生成器(坚持使用支持
1 2 3 4 5 6 7 8 9 10 | >>> 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'] >>> |
增加循环的
1 2 | for i * 100 in range(0, 100, 10): print i / 100.0 |
编辑:我真的不记得为什么我认为这会在语法上起作用
1 2 | for i in range(0, 11, 1): print i / 10.0 |
它应该具有所需的输出。
我觉得麻木有点过分了。
1 2 | [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 2 3 4 | 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] |
(当我测试时,
与r的
1 2 3 4 5 6 7 8 | 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([]) |
结果
1 | seq(1, 5, 0.5) |
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]
1 | seq(10, 0, -1) |
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
1 | seq(10, 0, -2) |
[10, 8, 6, 4, 2, 0]
1 | seq(1, 1) |
[ 1 ]
恐怕range()内置函数返回一个整数值序列,因此不能使用它来执行小数步。
我想说的是使用while循环:
1 2 3 4 | i = 0.0 while i <= 1.0: print i i += 0.1 |
如果您好奇,python正在将0.1转换为0,这就是为什么它告诉您参数不能为零的原因。
下面是使用ITertools的解决方案:
1 2 3 4 5 6 7 | 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) |
使用实例:
1 2 | for i in seq(0, 1, 0.1): print(i) |
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]
但是如果你使用:
1 | [ 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]
1 2 3 | import numpy as np for i in np.arange(0, 1, 0.1): print i |
如果经常这样做,您可能希望保存生成的列表
1 2 3 | r=map(lambda x: x/10.0,range(0,10)) for i in r: print i |
这是我获得浮动步数范围的解决方案。使用此功能,无需导入numpy,也无需安装它。我很确定它可以改进和优化。可以在这里发布。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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 2 3 | [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] |
我的版本使用原始范围函数为移位创建乘法索引。这允许对原始范围函数使用相同的语法。我做了两个版本,一个使用浮点,一个使用十进制,因为我发现在某些情况下,我想避免浮点算法引入的舍入漂移。
它与range/xrange中的空集合结果一致。
只向任意一个函数传递一个数值将返回标准范围输出到输入参数的整数上限值(因此,如果给它5.5,它将返回范围(6))。
编辑:下面的代码现在可以在pypi:franges上作为包提供
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | ## 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)) # [] |
1 2 3 4 5 | import more_itertools as mit for x in mit.numeric_range(0, 1, 0.1): print("{:.1f}".format(x)) |
产量
1 2 3 4 5 6 7 8 9 10 | 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 |
此工具也适用于
对于精品店的完整性,功能性解决方案:
1 2 | 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) |
可以使用numpy库来完成。函数的作用是:允许浮点运算。但是,它返回一个numpy数组,为了方便起见,可以使用tolist()将其转换为list。
1 2 | for i in np.arange(0, 1, 0.1).tolist(): print i |
我的答案与其他使用map()的方法类似,不需要numpy,也不使用lambda(尽管可以)。要获取从0.0到t_max的浮点值列表(以dt为单位):
1 2 3 | def xdt(n): return dt*float(n) tlist = map(xdt, range(int(t_max/dt)+1)) |
您可以使用此功能:
1 2 | def frange(start,end,step): return map(lambda x: x*step, range(int(start*1./step),int(end*1./step))) |
避免四舍五入问题的诀窍是使用一个单独的数字在范围内移动,即在开始前半步开始。
1 2 3 4 5 6 7 | # floating point range def frange(a, b, stp=1.0): i = a+stp/2.0 while i<b: yield a a += stp i += stp |
或者,可以使用
为可能出现错误的登录步骤添加自动更正:
1 2 3 | def frange(start,step,stop): step *= 2*((stop>start)^(step<0))-1 return [start+i*step for i in range(int((stop-start)/step))] |
最佳解决方案:无舍入误差
_________________________________________
1 2 3 4 5 | >>> 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] |
_________________________________________
或者,对于设定范围而不是设定数据点(例如连续函数),使用:
1 2 3 4 5 6 | >>> 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] |
实现功能:用
例如:
1 2 3 4 5 6 7 8 9 10 11 12 | >>> 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] |
启动和停止是包含的,而不是一个或另一个(通常不包括停止),没有导入和使用生成器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | 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, Jul 8 2017, 04:57:36) [MSC v.1900 64
bit (AMD64)]
我的解决方案:
1 2 3 4 5 6 7 | def seq(start, stop, step=1, digit=0): x = float(start) v = [] while x <= stop: v.append(round(x,digit)) x += step return v |
Suprised还没有人在python3文档中提到推荐的解决方案:
See also:
- The linspace recipe shows how to implement a lazy version of range that suitable for floating point applications.
一旦定义好,配方就很容易使用,不需要
1 2 3 4 | print(linspace(0, 10, 5)) # linspace(0, 10, 5) print(list(linspace(0, 10, 5))) # [0.0, 2.5, 5.0, 7.5, 10] |
我引用了AndrewBarnert的完整python3配方的修改版本,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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)) |
为了解决浮动精度问题,可以使用
这需要在编写代码时从
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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 |
样本输出-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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')] |
下面是我的解决方案,它可以很好地处理浮点范围(-1,0,0.01),并且不会出现浮点表示错误。它不是很快,但工作正常:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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] |
这一行程序不会使代码混乱。步骤参数的符号很重要。
1 2 3 | 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)] |
这里的许多解决方案在Python3.6中仍然存在浮点错误,并且没有完全按照我个人需要的方式进行处理。
下面的函数接受整数或浮点数,不需要导入,也不返回浮点错误。
1 2 3 4 5 6 7 8 9 | 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 |
弗兰奇(开始、停止、精确)
1 2 3 4 5 6 7 8 9 10 | 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] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | sign = lambda x: (1, -1)[x < 0] def frange(start, stop, step): i = 0 r=len(str(step).split('.')[-1]) args=(start,stop,step) if not step :return [] if all(int(i)==float(i) for i in args): start,stop,step=map(int,args) if sign(step)==1: while start + i * step < stop: yield round(start + i * step,r) i += 1 else: while start + i * step > stop: yield round(start + i * step,r) i += 1 |
我知道我迟到了,但这里有一个简单的生成器解决方案,它在3.6中工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def floatRange(*args): start, step = 0, 1 if len(args) == 1: stop = args[0] elif len(args) == 2: start, stop = args[0], args[1] elif len(args) == 3: start, stop, step = args[0], args[1], args[2] else: raise TypeError("floatRange accepts 1, 2, or 3 arguments. ({0} given)".format(len(args))) for num in start, step, stop: if not isinstance(num, (int, float)): raise TypeError("floatRange only accepts float and integer arguments. ({0} : {1} given)".format(type(num), str(num))) for x in range(int((stop-start)/step)): yield start + (x * step) return |
然后你可以像最初的
我只是个初学者,但在模拟计算时,我也遇到了同样的问题。下面是我试图解决这个问题的方法,它似乎是用小数步计算的。
我也很懒惰,所以我发现很难编写自己的范围函数。
基本上,我所做的是将我的
因此,我决定通过运行一个简短的测试来测试我的解决方案是否适用于我的范围:
1 2 3 4 | 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 |
每一张都是真的。
现在,如果我完全弄错了,请告诉我。