2

Good morning, when I use the below code, I get a wrong result

import numpy as np
print(np.convolve([10**9], [ 10**9]))

I am getting:-1486618624 while I should be getting: (10 to the power of 9) * (10 to the power of 9) = (10 to the power of 18)

How can I overcome this problem? It is very curious that I get the correct result by using:

print(np.convolve([10**10], [ 10**8]))

which gives me 1000000000000000000

while when I do:

print(np.convolve([10], [ 10**9]))

I get again a stupid result like 1410065408 rather than 10 to the power of 10. It looks like every time there is a 10 to the power of 9, I get strange results. Thanks

Francesco
  • 111
  • 9

1 Answers1

4

Note that 10**9 is an integer, which in numpy is interpreted as an int32, that is a 32-bit integer. The maximal value that can be represented in that type is 2147483647, if you go lager than that, you get an overflow. If you want to use integer types use np.int64 instead, otherwise use floating point numbers e.g. np.float:

np.convolve(np.array([10**9], dtype=np.int64), np.array([10**9], dtype=np.int64))
flawr
  • 10,814
  • 3
  • 41
  • 71
  • Thanks. Then why does it work with 10**10? And how can I fix it? – Francesco May 09 '21 at 22:09
  • 2
    If you use `10**10` it will create `int64` arrays from the start. Try it yourself: Print the `np.array([x]).dtype` for various values of `x`. Also check out the documentation: https://numpy.org/doc/stable/user/basics.types.html – flawr May 09 '21 at 22:09