Bug report

Peter Otten __peter__ at web.de
Wed Feb 24 15:57:29 EST 2021


On 24/02/2021 20:36, Carla Molina wrote:
> I found the following bug (python 3.9.1) when multiplying an array by
> several variables without parentheses; look at the following example:
> 
> import numpy as np
> 
> NR = 0.25
> N = 60461826
> 
> initialINCIDENCE = np.array([1, 50, 100, 150, 200, 250, 300])
> initialINCIDENCE = initialINCIDENCE*N/(100000*7*NR)
> print('First result ' +str(initialINCIDENCE))
> 
> initialINCIDENCE = np.array([1, 50, 100, 150, 200, 250, 300])
> initialINCIDENCE = initialINCIDENCE*(N/(100000*7*NR))
> print('Second result ' +str(initialINCIDENCE))
> 
> The result given is:
> 
> First result [   345.49614857  -7267.86283429  10006.94459429   2739.08176
>    -4528.78107429 -11796.64390857   5478.16352   ]
> Second result [   345.49614857  17274.80742857  34549.61485714
>   51824.42228571  69099.22971429  86374.03714286 103648.84457143]
> 
> Clearly both are different, and in particular the first one has no sense to
> me.

This is not a bug. Have a look at the array's dtype:

 >>> n = 60461826
 >>> a = np.array([1, 50, 100, 150, 200, 250, 300])
 >>> a.dtype
dtype('int32')

A 32-bit integer cannot hold the result of, e. g. 50 * n, the result is 
unhelpfully clipped.

One possible fix is to specify the array type:

 >>> b = np.array([1, 50, 100, 150, 200, 250, 300], dtype=float)
 >>> b * n
array([6.04618260e+07, 3.02309130e+09, 6.04618260e+09, 9.06927390e+09,
        1.20923652e+10, 1.51154565e+10, 1.81385478e+10])



More information about the Python-list mailing list