for with decimal values?

Ben Finney ben+python at benfinney.id.au
Sat May 2 19:48:34 EDT 2009


Esmail <ebonak at hotmail.com> writes:

> Hello all,
> 
> Is there a Python construct to allow me to do something like
> this:
> 
>    for i in range(-10.5, 10.5, 0.1):
>      ...

Note that those values are of type ‘float’, which is a distinct type
from ‘Decimal’ with very different behaviour.

> If there is such a thing already available, I'd like to use it,
> otherwise I can write a function to mimic this, but I thought I'd
> check (my search yielded nothing).

You can write a function to do it.

Alternatively, this case seems simple enough that you can write a
generator expression. Assuming you want ‘Decimal’ values:

    >>> from decimal import Decimal
    >>> amounts = (Decimal(mantissa)/10 for mantissa in range(-105, 105))
    >>> for amount in amounts:
    ...     print amount
    ...
    -10.5
    -10.4
    -10.3
    -10.2
    -10.1
    -10
    -9.9
    …
    9.6
    9.7
    9.8
    9.9
    10
    10.1
    10.2
    10.3
    10.4

-- 
 \      “I have a large seashell collection, which I keep scattered on |
  `\    the beaches all over the world. Maybe you've seen it.” —Steven |
_o__)                                                           Wright |
Ben Finney



More information about the Python-list mailing list