On Thu, 10 Dec 2015 08:57 am, Robert wrote:

> Hi,
> 
> I have a numpy np.array data x:
> 
> x= np.array([[157, 185], [169, 195], [162, 179], [145, 195], [159, 199],
>  [165, 180], [172, 195], [180, 201], [163, 195], [169, 191]])
> 
> Here is the original code snippet:
> 
> x+=uniform(-8, 8, x.shape)

What is "uniform"? I thought it might be numpy.uniform, but that doesn't
appear to exist. So I will guess that it might be numpy.random.uniform. Is
that right?


[...]
> I am curious about the integer data type of result x.

py> x = np.array([[157, 185], [169, 195], [162, 179], [145, 195], [159,
199],
...  [165, 180], [172, 195], [180, 201], [163, 195], [169, 191]])
py> x.dtype
dtype('int32')

py> y = np.random.uniform(-8, 8, x.shape)
py> y.dtype
dtype('float64')


So the array x is an array of int32 and the array of random numbers is an
array of float64.

When you do an in-place add using += the data type doesn't change, but when
you do an external add using + the result is coerced to the "wider" type,
which is float64.

py> x.dtype
dtype('int32')

py> (x + y).dtype
dtype('float64')


You can read up on numpy types here:

http://docs.scipy.org/doc/numpy/user/basics.types.html

http://docs.scipy.org/doc/numpy/reference/generated/numpy.find_common_type.html

http://docs.scipy.org/doc/numpy/reference/generated/numpy.result_type.html

http://docs.scipy.org/doc/numpy/reference/generated/numpy.promote_types.html


I'm not quite sure if the specific type promotion rules are documented
anywhere, but basically any arithmetic operation between different types
can involve loss of precision. Consider adding an integer 100 and a float
1.1, since they are different types, numpy must coerce the types to a
common format:

100 + int32(1.1) = 101

float64(100) + 1.1 = 101.1

Since the first result loses precision, numpy will choose the second. This
is called "type promotion": float64 can represent every value that int32
can, but int32 cannot represent every float64 without loss of precision.

When Numpy creates a new array as the result of an calculation, it will
promote the types involved to avoid data loss. But an in-place operation
like += has to use the type of the original, because that is fixed.


py> x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
py> x ** 0.5  # creates a new array
array([ 1.        ,  1.41421356,  1.73205081,  2.        ,  2.23606798,
        2.44948974,  2.64575131,  2.82842712,  3.        ])
py> x **= 0.5
py> x
array([1, 1, 1, 2, 2, 2, 2, 2, 3])



-- 
Steven

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to