确保小的舍入误差不会导致总和出现大误差的常用方法是检查每个部分总和的误差不会变得太大。
使用一维向量[a[1], a[2], ..., a[n]]
,您可以计算部分和[a[1], a[1]+a[2], ..., a[1]+a[2]+...+a[n]]
,将其相乘,然后通过将前一个单元格减去当前单元格来恢复良好的向量[a[1]*b, (a[1]+a[2])*b-a[1]*b, ..., (a[1]+a[2]+...+a[n])*b-(a[1]+a[2]+...+a[n-1])*b]
:通过使用这个技巧,任何部分和的误差都不会超过 10^(-x)。
您可以通过以下 3 个过程将此方法用于二维矩阵:
partial_sum(M) =
for i = 0 to n-1 do
for j = 1 to m-1 do
M[i][j] += M[i][j-1]
done
done
for i = 0 to n-1 do
for j = 1 to m-1 do
M[j][i] += M[j-1][i]
done
done
multiply(M, a) =
for i = 0 to n-1 do
for j = 0 to m-1 do
M[i][j] *= a
done
done
restore(M) =
for i = 0 to n-1 do
for j = 1 to m-1 do
M[i][j] -= M[i][j-1]
done
done
for i = 0 to n-1 do
for j = 1 to m-1 do
M[j][i] -= M[j-1][i]
done
done