简体   繁体   中英

Python: numpy data type casting

I'm confused by some output I'm seeing.

If p is a list of floats, what is the difference between:

input = np.array([p]).astype('f')

and

input = np.array([p],float)

If I use the second option and then do a print(input), I always get something like:

[array([-0.662, 0.246, 1.029])]

But if I use the first option, sometimes I get simply: [[ 0.61900002 1.71300006 2.16899991]]

but other times I get the [array([])] form.

here is the explanation:

In [217]: np.array([1.1,1.2,1.3]).astype('f')
Out[217]: array([ 1.10000002,  1.20000005,  1.29999995], dtype=float32)

In [218]: np.array([1.1,1.2,1.3]).astype('float')
Out[218]: array([ 1.1,  1.2,  1.3])

In [219]: np.array([1.1,1.2,1.3]).astype(float)
Out[219]: array([ 1.1,  1.2,  1.3])

Types:

In [220]: np.array([1.1,1.2,1.3]).astype(float).dtype
Out[220]: dtype('float64')

In [221]: np.array([1.1,1.2,1.3]).astype('f').dtype
Out[221]: dtype('float32')

so you will have the same result using np.array([p], 'f') :

In [224]: np.array([1.1,1.2,1.3],'f')
Out[224]: array([ 1.10000002,  1.20000005,  1.29999995], dtype=float32)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM