【问题标题】:Integer multiplication result is negative整数乘法结果为负
【发布时间】:2018-02-28 16:30:43
【问题描述】:

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

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

哪种 dtype 适合我的需求,或者我还能如何解决这个问题?

编辑:

当前的值都是(偶然相同)59049。但正如我所说,它们已经产生了错误并且可能会变得更高。我不能给你打印,因为这是在 Django 中完成的计算的一部分。

编辑 2:

正如在 cmets 中正确假设的那样,代码应该是 + 没有 *

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()

【问题讨论】:

  • 这一行之前的 x 和 y 中的值是什么?您能否在错误之前添加一个 print(x) 和 print(y) 以查看它们的值是什么?
  • 这段代码没有意义。可以简化为sum = a * b
  • @MarkDickinson:除了这不是hypot(截至目前)
  • @SergioTulentsev:是的。我看了一眼,把* 误认为+。不过,我不禁怀疑hypot 是 OP 真正想要的。
  • @MarkDickinson:是的,我也有这种怀疑。

标签: python python-3.x numpy


【解决方案1】:

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

应该解决您的问题的解决方案应该是将数字转换为浮点数(在操作之前: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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2017-08-17
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多