整数乘法结果为负

问题描述 投票:-2回答:1

我的两个正整数的乘法导致负值,因此我不能计算sqrt但得到一个math domain error。我的变量大小可以是10 ^ 10或更高。

sum = math.sqrt ( np.power( x , 2 ) * np.power( y , 2 ) )

哪种dtype适合我的需要或者我怎么能解决这个问题?

编辑:

这些值目前(偶然相同)59049.但正如我所说,他们已经创造了错误并且可以变得更高。我不能给你打印,因为这是在Django中完成的计算的一部分。

编辑2:

正如在评论中正确假设的那样,代码应该是+ no *

d.sum = math.sqrt( np.power(d.active , 2) + np.power(d.passive , 2))

更多背景:在我的项目的某一点,我得到一个矩阵,需要进行以下计算:

test = np.arange(9).reshape(3,3)
m = test
matrix= m.dot(m).dot(m).dot(m).dot(m)
activearray = matrix.sum(axis=1)
passivearray = matrix.sum(axis=0)

for idx, Descriptor.id in enumerate(projectdescriptors):
        d = Descriptor.objects.get(name=Descriptor.id)
        d.active = activearray[idx]
        d.passive = passivearray[idx]
        d.sum = math.sqrt( np.power(d.active , 2) + np.power(d.passive , 2))
        d.save()
python python-3.x numpy
1个回答
0
投票

正如评论中所述,您的问题是由于使用整数变量,结果会溢出并变为负值。

应该解决您的问题的解决方案应该是将数字转换为浮点数(在操作之前执行:x=x.astype(np.float32)),然后执行操作。

import numpy as np

x=np.array([3,3E18])
y=np.array([4,4E18])
dtypes=[np.int64,np.float32]

for dt in dtypes:
    x=x.astype(dt)
    y=y.astype(dt)
    z2=x**2+y**2
    z=np.sqrt(z2)
    print("Result with "+str(dt)+"=",z2,z)

结果:

Result with <class 'numpy.int64'>= [                  25 -9051522149004607488] [ 5. nan]
Result with <class 'numpy.float32'>= [2.5e+01 2.5e+37] [5.e+00 5.e+18]
© www.soinside.com 2019 - 2024. All rights reserved.