带有和不带有dtype的numpy.array行为很奇怪

编程入门 行业动态 更新时间:2024-10-09 11:28:03
本文介绍了带有和不带有dtype的numpy.array行为很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对此完全感到困惑。

从下面开始

import numpy as np a = np.array([4, -9]) a[0] = 0.4 a

我预期的输出: array([0.4,-9])。但这给了我

array([0,-9])。

但是当我将 dtype 更改为 f

a = np.array([4, -9], 'f') a[0] = 0.4 a

它给了我 array([0.40000001,-9。],dtype = float32)

numpy.array(object,dtype = None,copy = True,order ='的文档K',subok = False,ndmin = 0)说:

dtype:数据类型,可选数组的所需数据类型。如果未给出,则将类型确定为在序列中保存对象所需的最小类型。此参数只能用于上载阵列。对于向下转换,请使用.astype(t)方法。

dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.

当我初始化数组时,它将值初始化为整数,所以当我用 float 为数组建立索引时,它只能识别整数 0.4 的一部分,因此给了我 0 。这就是我的理解。这样对吗?。但是我仍然对这种行为感到惊讶。

When I initialized the array it initialized the values to integers and so when I indexed the array with a float it only recognized the integer part of 0.4 and hence gave me 0. This is how I understand it. Is this correct?. But I am still surprised by this behavior.

问题:这到底是怎么回事?

Question: What exactly is going on here?

推荐答案

问题是您的数组为 dtype = np.int64 :

In [141]: a = np.array([4, -9]) In [142]: a.dtype Out[142]: dtype('int64')

这意味着您只能存储整数,并且所有浮点数都会在分配完成之前被截断。如果要将浮点数和整数存储在一起,则应首先指定 dtype = object :

This means that you can only store integers, and any floats are truncated before assignment is done. If you want to store floats and ints together, you should specify dtype=object first:

In [143]: a = np.array([4, -9], dtype=object) In [144]: a[0] = 0.4 In [145]: a Out[145]: array([0.4, -9], dtype=object)

关于 array([0.40000001,-9。] , 0.4 ,因为浮点数在内存中没有确切的表示形式(只有一个近似值),这说明了您看到的不精确性。

As for the issue with array([ 0.40000001, -9. ], 0.4, as a floating point number does not have an exact representation in memory (only an approximate one), which accounts for the imprecision you see.

更多推荐

带有和不带有dtype的numpy.array行为很奇怪

本文发布于:2023-10-30 07:35:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542198.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:很奇怪   dtype   numpy   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!