182

Is there a range() equivalent for floats in Python?

>>> range(0.5,5,1.5)
[0, 1, 2, 3, 4]
>>> range(0.5,5,0.5)

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    range(0.5,5,0.5)
ValueError: range() step argument must not be zero
4

23 に答える 23

140

次のいずれかを使用できます。

[x / 10.0 for x in range(5, 50, 15)]

またはラムダ/マップを使用します:

map(lambda x: x/10.0, range(5, 50, 15))
于 2011-09-01T07:36:25.870 に答える
107
組み込み関数はわかりませんが、 [this](https://stackoverflow.com/a/477610/623735) のようなものを書くのはそれほど複雑ではありません。
def frange(x, y, jump):
  while x < y:
    yield x
    x += jump
---

コメントが言及しているように、これは次のような予測できない結果をもたらす可能性があります。

>>> list(frange(0, 100, 0.1))[-1]
99.9999999999986

期待される結果を得るには、この質問の他の回答のいずれかを使用するか、@Tadhg が言及したように、引数decimal.Decimalとして使用できます。jumpfloat ではなく文字列で初期化してください。

>>> import decimal
>>> list(frange(0, 100, decimal.Decimal('0.1')))[-1]
Decimal('99.9')

あるいは:

import decimal

def drange(x, y, jump):
  while x < y:
    yield float(x)
    x += decimal.Decimal(jump)

その後:

>>> list(drange(0, 100, '0.1'))[-1]
99.9

jump[編集者の注意: 正と整数の start と stop ( xand )のみを使用する場合y、これは正常に機能します。より一般的な解決策については、こちらを参照してください。]

于 2011-09-01T07:36:01.510 に答える
95

以前は使用してnumpy.arangeいましたが、浮動小数点エラーが原因で、返される要素の数を制御するのにいくつかの複雑さがありました。だから今私は使用しますlinspace、例えば:

>>> import numpy
>>> numpy.linspace(0, 10, num=4)
array([  0.        ,   3.33333333,   6.66666667,  10.        ])
于 2011-09-01T08:30:55.180 に答える
41

Pylabにはfrange(実際にはラッパーがありますmatplotlib.mlab.frange):

>>> import pylab as pl
>>> pl.frange(0.5,5,0.5)
array([ 0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ])
于 2013-02-01T19:07:07.087 に答える
14

熱心に評価 (2.x range):

[x * .5 for x in range(10)]

遅延評価 (2.x xrange、 3.x range):

itertools.imap(lambda x: x * .5, xrange(10)) # or range(10) as appropriate

別の方法:

itertools.islice(itertools.imap(lambda x: x * .5, itertools.count()), 10)
# without applying the `islice`, we get an infinite stream of half-integers.
于 2011-09-01T07:40:16.300 に答える
5

そのような組み込み関数はありませんが、次の (Python 3 コード) を使用して、Python で可能な限り安全に作業を行うことができます。

from fractions import Fraction

def frange(start, stop, jump, end=False, via_str=False):
    """
    Equivalent of Python 3 range for decimal numbers.

    Notice that, because of arithmetic errors, it is safest to
    pass the arguments as strings, so they can be interpreted to exact fractions.

    >>> assert Fraction('1.1') - Fraction(11, 10) == 0.0
    >>> assert Fraction( 0.1 ) - Fraction(1, 10) == Fraction(1, 180143985094819840)

    Parameter `via_str` can be set to True to transform inputs in strings and then to fractions.
    When inputs are all non-periodic (in base 10), even if decimal, this method is safe as long
    as approximation happens beyond the decimal digits that Python uses for printing.


    For example, in the case of 0.1, this is the case:

    >>> assert str(0.1) == '0.1'
    >>> assert '%.50f' % 0.1 == '0.10000000000000000555111512312578270211815834045410'


    If you are not sure whether your decimal inputs all have this property, you are better off
    passing them as strings. String representations can be in integer, decimal, exponential or
    even fraction notation.

    >>> assert list(frange(1, 100.0, '0.1', end=True))[-1] == 100.0
    >>> assert list(frange(1.0, '100', '1/10', end=True))[-1] == 100.0
    >>> assert list(frange('1', '100.0', '.1', end=True))[-1] == 100.0
    >>> assert list(frange('1.0', 100, '1e-1', end=True))[-1] == 100.0
    >>> assert list(frange(1, 100.0, 0.1, end=True))[-1] != 100.0
    >>> assert list(frange(1, 100.0, 0.1, end=True, via_str=True))[-1] == 100.0

    """
    if via_str:
        start = str(start)
        stop = str(stop)
        jump = str(jump)
    start = Fraction(start)
    stop = Fraction(stop)
    jump = Fraction(jump)
    while start < stop:
        yield float(start)
        start += jump
    if end and start == stop:
        yield(float(start))

いくつかのアサーションを実行することで、すべてを確認できます。

assert Fraction('1.1') - Fraction(11, 10) == 0.0
assert Fraction( 0.1 ) - Fraction(1, 10) == Fraction(1, 180143985094819840)

assert str(0.1) == '0.1'
assert '%.50f' % 0.1 == '0.10000000000000000555111512312578270211815834045410'

assert list(frange(1, 100.0, '0.1', end=True))[-1] == 100.0
assert list(frange(1.0, '100', '1/10', end=True))[-1] == 100.0
assert list(frange('1', '100.0', '.1', end=True))[-1] == 100.0
assert list(frange('1.0', 100, '1e-1', end=True))[-1] == 100.0
assert list(frange(1, 100.0, 0.1, end=True))[-1] != 100.0
assert list(frange(1, 100.0, 0.1, end=True, via_str=True))[-1] == 100.0

assert list(frange(2, 3, '1/6', end=True))[-1] == 3.0
assert list(frange(0, 100, '1/3', end=True))[-1] == 100.0

GitHubで利用可能なコード

于 2016-12-22T02:17:39.193 に答える
1

100 分の 1 を超える小数点以下の桁数を含まない倍精度浮動小数点数の範囲のタプルを返す関数を作成しました。文字列のように範囲値を解析し、余分な部分を分割するだけでした。UI 内から選択する範囲を表示するために使用します。他の誰かがそれを役に立つと思うことを願っています。

def drange(start,stop,step):
    double_value_range = []
    while start<stop:
        a = str(start)
        a.split('.')[1].split('0')[0]
        start = float(str(a))
        double_value_range.append(start)
        start = start+step
    double_value_range_tuple = tuple(double_value_range)
   #print double_value_range_tuple
    return double_value_range_tuple
于 2015-11-19T04:53:40.433 に答える
-1

Pythonのフロートに相当するrange()はありますか? いいえこれを使用します:

def f_range(start, end, step, coef=0.01):
    a = range(int(start/coef), int(end/coef), int(step/coef))
    var = []
    for item in a:
        var.append(item*coef)
    return var
于 2017-01-12T10:00:28.200 に答える