[Tutor] math question
Karl Pflästerer
sigurd at 12move.de
Fri Apr 23 11:16:04 EDT 2004
On 23 Apr 2004, Chris Lott < chris at chrislott.org wrote:
> Given below, why isn't the answer ever "right"?
> >>> math.sqrt(2) * math.sqrt(2)
> 2.0000000000000004
> >>> (math.sqrt(2))**2
> 2.0000000000000004
Here are several problems:
(a) sqrt(2) can't be written as exact value (neither base 10 nor base
2). So Python uses a floating point approximation
(b) you see the internal representation of the numbers (repr())
(c) most floating point numbers can't be represented exactly in the way
Python stores them
A very good explanation of the problems with floating point numbers can
be found in the Python tutorial in the official documentation. You
should read it.
A simple example from it which shows the problem:
,[ Python tutorial: Floating Point Arithmetic: Issues and Limitations]

 The problem is easier to understand at first in base 10. Consider the
 fraction 1/3. You can approximate that as a base 10 fraction:

 0.3

 or, better,

 0.33

 or, better,

 0.333

 and so on. No matter how many digits you're willing to write down, the
 result will never be exactly 1/3, but will be an increasingly better
 approximation to 1/3.

 In the same way, no matter how many base 2 digits you're willing to
 use, the decimal value 0.1 cannot be represented exactly as a base 2
 fraction. In base 2, 1/10 is the infinitely repeating fraction

 0.0001100110011001100110011001100110011001100110011...

 Stop at any finite number of bits, and you get an approximation. This
 is why you see things like:

 >>> 0.1
 0.10000000000000001
`
Karl

Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list