提前道歉-我似乎有一个很根本的误解,我无法澄清。我有一个fourvector类,有ct和位置向量的变量。我在写代码来执行x方向的洛伦兹增强。我遇到的问题是,正如下面所写的,ct返回一个适当的浮点值,但x没有。搞砸了,我发现tempx是一个float,但是将tempx赋给r[0]并不能使其成为float,而是取而代之的是一个整数。我之前曾发表过一个关于可变性与不变性的问题,我怀疑这就是问题所在。如果是这样,我显然有一个比预期更深的误解。不管怎样,我有几个问题要问
1a)如果用a=FourVector(ct=5,r=[55,2,3])实例化a,则类型(a.\u r[0])返回数字浮点数64与之相反数字.int32. 这是怎么回事?我只希望一个..\u r[1]是一个浮点,而它却改变了整个列表的类型?在
1b)如何获得上述行为(整个列表是浮动的),而不必将变量实例化为浮动?我阅读了文档并尝试了各种方法,比如使用astype(float),但是我所做的一切似乎都将其作为一个int来保存。在
2)我原以为,在这个时候。。。线,乘以1.0会将它转换成一个浮点数,因为看起来这就是ct转换为浮点数的原因,但由于某些原因它没有。也许和其他原因一样?在
import numpy as np
class FourVector():
def __init__(self, ct=0, x=0, y=0, z=0, r=[]):
self._ct = ct
self._r = np.array(r)
if r == []:
self._r = np.array([x,y,z])
def boost(self, beta):
gamma=1/np.sqrt(1-(beta ** 2))
tempct=(self._ct*gamma-beta*gamma*self._r[0])
tempx=(-1.0*self._ct*beta*gamma+self._r[0]*gamma)
self._ct=tempct
print(type(self._r[0]))
self._r[0]=tempx.astype(float)
print(type(self._r[0]))
a = FourVector(ct=5,r=[55,2,3])
b = FourVector(ct=1,r=[4,5,6])
print(a._r)
a.boost(.5)
print(a._r)
你所有的问题都是相关的。在
numpy数组是一种有效地保存对象的数组。它通过让这些对象具有相同的类型,比如字符串(等长)或整数或浮点。然后,它可以很容易地计算出每个元素需要多少空间以及它必须“跳转”多少字节才能访问下一个元素(我们称之为“跨步”)。在
当您从一个列表创建一个数组时,numpy将尝试从该列表中确定一个合适的数据类型(“dtype”),以确保所有元素都能被很好地表示出来。只有当您显式地指定数据类型时,它才不会做出有根据的猜测。在
考虑以下示例:
如您所见,在我的系统中,它返回一个
int64
的数据类型,这是使用8字节的整数表示。它选择这样做是因为:现在考虑更改该数组的尝试:
^{pr2}$如您所见,一旦设置了数组的数据类型,就完成了对该数据类型的自动转换。 现在让我们考虑一下当您传入至少有一个浮点的列表时会发生什么:
再次,numpy为这个数组确定一个合适的数据类型。在
盲目尝试更改数组的数据类型是不明智的:
你可能会说这些数字是胡言乱语。这是因为numpy试图将数组的内存位置重新解释为4字节的浮点(熟练的人员将能够将数字转换为二进制表示,并从那里重新解释原始整数值)。在
如果要强制转换,则必须显式地执行该操作,numpy将返回一个new数组:
现在,请回答您的具体问题:
这是因为numpy必须为整个数组确定一个数据类型(除非使用structured array),以确保所有元素都适合该数据类型。只有这样,numpy才能有效地迭代该数组的元素。在
创建数组时指定
dtype
。在您的代码中,这将是:这是真的。尝试打印
tempx
的数据类型,它应该是一个float。但是,稍后,您将把这个值重新插入数组self._r
,它的数据类型为int。正如您前面看到的,这将把float转换回整数类型。在相关问题 更多 >
编程相关推荐