社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

For循环范围步骤更改为float python[duplicate]

Deivids Agriņš • 5 年前 • 2911 次点击  

有没有办法在0和1之间按0.1步进?

我以为我可以像下面这样做,但失败了:

for i in range(0, 1, 0.1):
    print i

相反,它说步骤参数不能为零,这是我没有预料到的。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49603
 
2911 次点击  
文章 [ 30 ]  |  最新文章 5 年前
zred
Reply   •   1 楼
zred    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]
Tjaart
Reply   •   2 楼
Tjaart    11 年前

这一行不会弄乱你的代码。的标志 参数很重要。

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)]
user2836437
Reply   •   3 楼
user2836437    11 年前

我只是一个初学者,但是我在模拟一些计算时遇到了同样的问题。下面是我试图解决这个问题的方法,它似乎是用小数步来计算的。

我也很懒,所以我发现很难编写自己的范围函数。

基本上我所做的改变 xrange(0.0, 1.0, 0.01) xrange(0, 100, 1) 使用除法 100.0 在圈内。 我也很担心,是否会出现舍入错误。所以我决定测试一下,有没有。我听说如果 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

每一个都是真的。

现在,如果我完全弄错了,请告诉我。

pymen
Reply   •   4 楼
pymen    12 年前

这是我的解决方案,它在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]
Chris_Rands
Reply   •   5 楼
Chris_Rands    7 年前

令人惊讶的是,还没有人提到推荐的解决方案 in the Python 3 docs :

另见:

  • 这个 linspace recipe 演示如何实现适合浮点应用程序的范围的延迟版本。

一旦定义,配方很容易使用,不需要 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]

我引用安德鲁·巴内特(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))
Goran B.
Reply   •   6 楼
Goran B.    7 年前

启动和停止是包含的,而不是一个或另一个(通常不包括停止),并且没有导入和使用生成器

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")))

蟒蛇3.6.2(v3.6.2:5fd33b5,2017年7月8日,04:57:36)[MSC v.1900 64 钻头(AMD64)]

jason
Reply   •   7 楼
jason    8 年前

最佳解决方案: 无舍入误差
_________________________________________________________________________________

>>> 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]
Peter Mortensen Jjen
Reply   •   8 楼
Peter Mortensen Jjen    12 年前

我的解决方案:

def seq(start, stop, step=1, digit=0):
    x = float(start)
    v = []
    while x <= stop:
        v.append(round(x,digit))
        x += step
    return v
BobH
Reply   •   9 楼
BobH    14 年前

添加对可能出现错误登录步骤的自动更正:

def frange(start,step,stop):
    step *= 2*((stop>start)^(step<0))-1
    return [start+i*step for i in range(int((stop-start)/step))]
shad0w_wa1k3r
Reply   •   10 楼
shad0w_wa1k3r    7 年前

为了解决浮点精度问题,可以使用 Decimal module .

这需要付出额外的努力 十进制的 int float 在编写代码时,但是您可以通过 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')]
Eric Myers
Reply   •   11 楼
Eric Myers    8 年前

我的答案与其他使用map()的方法类似,不需要NumPy,也不使用lambda(尽管您可以)。要以dt为单位获取从0.0到t_max的浮点值列表:

def xdt(n):
    return dt*float(n)
tlist  = map(xdt, range(int(t_max/dt)+1))
user3654478
Reply   •   12 楼
user3654478    9 年前

它可以使用Numpy库来完成。函数的作用是:允许在float中执行步骤。但是,它返回一个numpy数组,为了方便起见,可以使用to list()将其转换为list。

for i in np.arange(0, 1, 0.1).tolist():
   print i
wolfram77
Reply   •   13 楼
wolfram77    9 年前

避免的诀窍 舍入问题 就是用一个单独的数字在范围内移动 一半 这个 领先 开始 .

# 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 可以使用。

Peter Mortensen Jjen
Reply   •   14 楼
Peter Mortensen Jjen    12 年前

您可以使用此功能:

def frange(start,end,step):
    return map(lambda x: x*step, range(int(start*1./step),int(end*1./step)))
pylang
Reply   •   15 楼
pylang    7 年前

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

此工具也适用于 Decimal Fraction .

Bijou Trouvaille
Reply   •   16 楼
Bijou Trouvaille    9 年前

对于精品店的完整性,功能解决方案:

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)
Carlos Vega
Reply   •   17 楼
Carlos Vega    11 年前

这是我的解决方案,以获得浮动步骤的范围。
使用此函数不需要导入或安装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]
Nisan.H
Reply   •   18 楼
Nisan.H    12 年前

我的版本使用原始的range函数为移位创建乘法索引。这允许对原始范围函数使用相同的语法。 我做了两个版本,一个使用浮点,一个使用十进制,因为我发现在某些情况下,我想避免浮点算法引入的舍入漂移。

与range/xrange中的空集结果一致。

只向任一函数传递一个数值将返回标准范围输出到输入参数的整数上限值(因此,如果给它5.5,它将返回范围(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)) # []
RSabet
Reply   •   19 楼
RSabet    16 年前

如果您经常这样做,您可能需要保存生成的列表 r

r=map(lambda x: x/10.0,range(0,10))
for i in r:
    print i
Steve Czetty Raja
Reply   •   20 楼
Steve Czetty Raja    12 年前
import numpy as np
for i in np.arange(0, 1, 0.1): 
    print i