我想添加两个3x2矩阵g
和temp_g
。
目前g
是
[[ 2.77777778e+000 6.58946653e-039]
[ 4.96398713e+173 1.64736663e-039]
[ -1.88888889e+000 -3.29473326e-039]]
temp_g
是:
[[ -5.00000000e-01 -2.77777778e+00]
[ -1.24900090e-16 -4.44444444e-01]
[ 5.00000000e-01 1.88888889e+00]]
但当我执行g = g + temp_g
并输出g
时,我明白了:
[[ 2.27777778e+000 -2.77777778e+000]
[ 4.96398713e+173 -4.44444444e-001]
[ -1.38888889e+000 1.88888889e+000]]
也许我在理解长期浮点数时遇到了麻烦......但结果应该是什么呢?我希望将g[0][0]
添加到temp_g[0][0]
,将g[0][1]
添加到temp_g [0][1]
等等......
答案 0 :(得分:4)
您的添加工作正常,但您的两个阵列有一些严重不同的数量级。
以4.96398713e+173 - 1.24900090e-16
为例,您的第一个数字比第二个数字大189个数量级。浮点数不具备此级别或准确性,您谈论的是在数字末尾用~170 0s
说出一个数字并添加0.00000000000000001249
行的数字它。
我建议查看this以查看浮点数的一些限制(在所有语言中,不一定是Python)。
Decimal
库可用于比浮点数更准确地处理数字。
import numpy as np
import decimal
a = decimal.Decimal(4.96398713e+173)
b = decimal.Decimal(1.24900090e-16)
print(a+b)
# 4.963987129999999822073620193E+173
# You can also set the dtype of your array to decimal.Decimal
a = np.array([[ 2.77777778e+000, 6.58946653e-039],
[ 4.96398713e+173, 1.64736663e-039],
[ -1.88888889e+000, -3.29473326e-039]],
dtype=np.dtype(decimal.Decimal))