Search code examples
pythonarraysnumpyprecisionexponentiation

numpy exponentiation with ** on integer array vs float array


Why do I get a difference between ** operating on a float array and on an integer array?

  1. What is ** doing differently on the integer array than on a float array?
  2. Is this some sort of a rounding problem with machine precision?
  3. And why is it only an issue with an array and not when I type it out?

MWE: why is f(ns) not equal f(fs)

import numpy as np
def f(x):
    a = +x**5
    b = +x**6 
    return a-b

ns = np.array([60])   #integers
fs = np.array([60.])  #floats

print(ns)
print(fs)

print(f(ns))
print(f(fs))

print(int(60)**5- int(60)**6)
print(60.**5 - 60.**6)

resulting in

[60]
[60.]

[1366240256]
[-4.58784e+10]

-45878400000
-45878400000.0

Solution

  • Because np.int32 and int are different things. In other words, elements of numpy integer array are not Python integers.

    In Python, int is an arbitrary length integer. You may calculate 123**45 and get a 90+ digit integer number, which is exactly 123**45 .

    In numpy, elements of array are standard 32-bit or 64-bit (or sometimes 8 or 16 bit) integers, and arithmetic operators standard CPU arithmetics. In this case, numbers are almost certainly signed or unsigned 32-bit. So it calculates 60**6 with 32-bit integers. Since it does not fit into 32 bits, the result is something like 606 modulo 232.