[Python-ideas] Python Numbers as Human Concept Decimal System
Stefan Krah
stefan at bytereef.org
Sat Mar 8 15:18:20 CET 2014
Mark Dickinson <dickinsm at gmail.com> wrote:
> I see three sane options for float to Decimal conversion:
>
> 1. Raise an exception.
> 2. Round to the nearest Decimal value using the current context for that round
> operation.
> 3. Do what we're currently doing, and do an exact conversion.
I agree that these are the main reasonable options. All functions
in Cowlishaw's specification use all digits from overlong input
operands, so there should be a convenient way of creating such
operands exactly.
I think we should not make an exeception for floats, unless we move into
the direction of IEEE 754-2008 (but that surely is a different topic).
Some general comments:
The current model works well, since we already have a fallback
constructor that rounds:
>>> from decimal import *
>>> context = getcontext()
>>> Decimal(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')
>>> context.create_decimal(1.1)
Decimal('1.10')
>>>
If you want safety against accidental conversions, set FloatOperation:
>>> context.traps[FloatOperation] = True
>>> Decimal(1.1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
If you want extra safety against *any* accidental float comparisons,
check the flags manually. This is necessary, since equality operations
cannot raise due to the fact that they are also used for membership
testing:
>>> context.clear_flags()
>>> Decimal(9) in [9.0]
True
>>> if context.flags[FloatOperation]:
... raise FloatOperation
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
decimal.FloatOperation
You see that the float operation is still recorded, even though it
isn't raised automatically. Such a check could be done periodically
or at the end of a program.
To summarize, I think we should leave things as they are or turn on
FloatOperation by default.
Stefan Krah
More information about the Python-ideas
mailing list