数组的列式总和-两种方法,两种不同的结果 [英] Columnwise sum of array - two methods, two different results

查看:110
本文介绍了数组的列式总和-两种方法,两种不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,以两种不同的方式计算数组pr的按列求和:

In this example, the column-wise sum of an array pr is computed in two different ways:

(a)使用p.sumaxis参数

(b)沿第二个轴对数组进行切片,并获取每个切片的总和

(b) slice the array along the the second axis and take the sum of each slice

import matplotlib.pyplot as plt
import numpy as np


m = 100
n = 2000
x = np.random.random_sample((m, n))

X = np.abs(np.fft.rfft(x)).T
frq = np.fft.rfftfreq(n)

total = X.sum(axis=0)
c = frq @ X / total

df = frq[:, None] - c
pr = df * X


a = np.sum(pr, axis=0)
b = [np.sum(pr[:, i]) for i in range(m)]

fig, ax = plt.subplots(1)
ax.plot(a)
ax.plot(b)
plt.show()

两个方法都应该返回相同的结果,但是由于某种原因,在此示例中,它们都不返回.如下图所示,ab具有完全不同的值.但是,差异是如此之小,以致np.allclose(a, b)为True.

Both methods should return the same, but for whatever reason, in this example, they do not. As you can see in the plot below, a and b have totally different values. The difference is, however, so small that np.allclose(a, b) is True.

如果将pr替换为一些较小的随机值,则两种求和方法之间没有区别:

If you replace pr with some small random values, there is no difference between the two summation methods:

pr = np.random.randn(n, m) / 1e12
a = np.sum(pr, axis=0)
b = np.array([np.sum(pr[:, i]) for i in range(m)])

fig, ax = plt.subplots(1)
ax.plot(a)
ax.plot(b)
plt.show()

第二个例子表明,第一个例子的和之差与求和方法无关.那么,这是一个与浮点值求和有关的问题吗?如果是这样,为什么在第二个示例中没有出现这种效果?

The second example indicates that the differences in the sums of the first example are not related to the summation methods. Then, is this a problem relate to floating point value summation? If so, why doesn't such an effect occure in the second example?

为什么第一个示例中的按列求和不同,哪个是正确的?

Why do the colum-wise sums differ in the first example, and which one is correct?

推荐答案

为什么结果不同,请参见 https://stackoverflow .com/a/55469395/7207392 .切片情况使用成对求和,轴情况不使用.

For why the results are different, see https://stackoverflow.com/a/55469395/7207392. The slice case uses pairwise summation, the axis case doesn't.

哪个是正确的?好吧,也许两者都不行,但是成对求和预计会更准确.

Which one is correct? Well, probably neither, but pairwise summation is expected to be more accurate.

实际上,我们可以看到它非常接近使用math.fsum获得的精确(在机器精度范围内)结果.

Indeed, we can see that it is fairly close to the exact (within machine precision) result obtained using math.fsum.

这篇关于数组的列式总和-两种方法,两种不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆