Confusing math problem

Steven D'Aprano steve+comp.lang.python at
Fri Feb 22 10:27:20 CET 2013

On Thu, 21 Feb 2013 19:33:32 +0000, Schizoid Man wrote:

> Hi there,
> I run the following code in Python 3.3.0 (on a Windows 7 machine) and
> Python 2.7.3 on a Mac and I get two different results:

Others have already explained that math.pow and the ** exponentiation 
operator are subtly different. However I wish to discuss your code:

> result1 = []
> result2 = []
> for a in range(2,101):
>     for b in range(2,101):
>         result1.append(math.pow(a,b))
>         result2.append(a**b)
> result1 = list(set(result1))
> result2 = list(set(result2))
> print (len(result1))
> print (len(result2))

This is more simply written as:

result1 = set()
result2 = set()
for a in range(2, 101):
    for b in range(2, 101):
        result2.add(math.pow(a, b))


No need for the pointless conversion from list to set to list again, if 
all you want is the number of unique values.

More interesting is to gather the pairs of values that differ:

results = []
for a in range(2, 101):
    for b in range(2, 101):
        if a**b != math.pow(a, b): results.append((a, b))

You will see that integer exponentiation and floating point 
exponentiation are more frequently different than not.

(8105 of the calculations differ, 1696 of them are the same.)


More information about the Python-list mailing list