What is considered an "advanced" topic in Python?

BartC bc at freeuk.com
Mon Jun 1 08:24:22 EDT 2015


On 01/06/2015 12:24, Laura Creighton wrote:

> Maybe _your_ brain needs some resetting, too. :)  You know too much so
> have lost the grasp of how the world looks to the new programmer.

Maybe the new programmer should learn then that binary floating point 
might not perform as they might expect.

I'm sure it wasn't long after I first started programming that I 
discovered the reason why code such as:

  for i:=0.0 until 10.0 step 0.1 ...     # (Algol 60)

might not always work properly.

I don't think using decimal magically solves all problems either:

  a=decimal.Decimal('0.0')
  b=decimal.Decimal('1.0')/decimal.Decimal('3.0')
  c=decimal.Decimal('10.0')

  while a<=c:
	print (a)
	a=a+b

This prints 9.999... as the final value rather than 10.0. And if changed to:

  while a!=c:
      .....

then this doesn't terminate.

> I want to use a computer to add up a whole lot of money amounts so I can
> figure out how much money to send some place.
>
> This is an absolute, dead simple first computer program newbies write.
> For a lot of people, this used to be the whole reason they bought a
> computer in the first place.

How many people who buy phones are actually going to write their own 
programs? Rather than download an app written by people who can code (or 
use the built-in calculator). (How do you even code in Python on a 
smartphone anyway?)

> And they immediately grab floating point numbers, and since adding
> a whole lot of them in range of 'prices for stuff at the supermarket'
> is one of the best ways to guarantee your will not get the correct,
> exact amount you want for your answer, they don't get it.

Also, how many items need to be added up before even 64-bit floating 
point values show a discrepancy, after rounding to whole cents? Or are 
we adding up billions of dollars and expecting a result to the exact cent?

> But I am a bad arguer.
>
> When incompatibilites were going into Python 3.0 I wanted
>
> y = 1.3  to give you a decimal, not a float.

1.3 yielding floating point is fairly universal. Probably there would be 
bigger problems if 1.3 silently gave you a decimal type.

> But, hell, I write accounting and bookkeeping systems.  Your milage
> may vary. :)

You can emulate decimal floating point with binary floating point, if 
the latter has some spare precision. Or an easy fix for the shopping 
problem is to work in whole cents, using either integer or floating 
point (although the latter limits you to some $50 trillion dollars for 
the total, which might be a problem if we ever get hyper-inflation again).

But if the numeric representation is crucial to your application, then 
surely you just create a custom type or class for that? (I think Python 
is quite good at this sort of customising; I lot of Python code I see 
now seems to consist of nothing else!)

-- 
Bartc




More information about the Python-list mailing list