[Python-ideas] Python Float Update

Steven D'Aprano steve at pearwood.info
Tue Jun 2 03:37:48 CEST 2015

On Mon, Jun 01, 2015 at 05:52:35PM +0300, Joonas Liik wrote:

> Having some sort of decimal literal would have some advantages of its own,
> for one it could help against this sillyness:
> >>> Decimal(1.3)
> Decimal('1.3000000000000000444089209850062616169452667236328125')

Why is that silly? That's the actual value of the binary float 1.3 
converted into base 10. If you want 1.3 exactly, you can do this:

> >>> Decimal('1.3')
> Decimal('1.3')

Is that really so hard for people to learn? 

> I'm not saying that the actual data type needs to be a decimal (
> might well be a float but say shove the string repr next to it so it can be
> accessed when needed)

You want Decimals to *lie* about what value they have?

I think that's a terrible idea, one which would lead to a whole set of 
new and exciting surprises when using Decimal. Let me try to predict a 
few of the questions on Stackoverflow which would follow this change...

  Why is equality so inaccurate in Python?

  py> x = Decimal(1.3)
  py> y = Decimal('1.3')
  py> x, y
  (Decimal('1.3'), Decimal('1.3'))
  py> x == y

  Why does Python insert extra digits into numbers when I multiply?

  py> x = Decimal(1.3)
  py> x
  py> y = 10000000000000000*x
  py> y - 13000000000000000

> ..but this is one really common pitfall for new users, i know its easy to
> fix the code above,
> but this behavior is very unintuitive.. you essentially get a really
> expensive float when you do the obvious thing.

Then don't do the obvious thing.

Sometimes there really is no good alternative to actually knowing what 
you are doing. Floating point maths is inherently hard, but that's not 
the problem. There are all sorts of things in programming which are 
hard, and people learn how to deal with them. The problem is that people 
*imagine* that floating point is simple, when it is not and can never 
be. We don't do them any favours by enabling that delusion.

If your needs are light, then you can ignore the complexities of 
floating point. You really can go a very long way by just rounding the 
results of your calculations when displaying them. But for anything more 
than that, we cannot just paper over the floating point complexities 
without creating new complexities that will burn people.

You don't have to become a floating point guru, but it really isn't 
onerous to expect people who are programming to learn a few basic 
programming skills, and that includes a few basic coping strategies for 
floating point.


More information about the Python-ideas mailing list