Matlab - 如何求和 1 到 1E10 系列的 1/x 最优(几分钟内) - matlab 变慢

Matlab - How to sum 1 to 1E10 serie of 1/x optimaly (in a few minutes) - matlab slows down

我对 matlab 有疑问。我需要对从 1 到 1E10 的数学系列 1/x 求和。我在 Matlab 中有一些包含循环的代码 - 第一个循环步骤可以非常快),但是在循环的第二个步骤中它变慢并且 Matlab 几乎被冻结,所以我无法在适当的时间计算它。

你能帮我解决这个问题吗?

对于较小的范围它工作正常(例如 1E06),但我需要计算整个范围。我试图分离到更小的范围,但仍然存在循环并且 matlab 非常慢。

好像是matlab和for循环的问题,变慢了。在第一个循环步骤之后,RAM 已满,但对于第二个循环步骤,RAM 仍然是满的,因此速度变慢。我不知道为什么 Matlab 不释放 RAM。

感谢您的帮助!

弗拉基米尔

你想获得第1e10个harmonic number. In the Symbolic Toolbox there is a function for that, called harmonic,而且速度很快:

>> format long %// to see more decimals
>> n = 1e10;
>> harmonic(n)
ans =
  23.603066594891992

之所以这么快是因为 harmonic 函数利用了 relationship between harmonic numbers, the Euler-Mascheroni constant and the digamma function:


其中"psi"是digamma函数,Hn n次谐波数,"gamma"为Euler-Mascheroni常数。所以你也可以使用

>> n = 1e10;
>> vpa(psi(n+1) + eulergamma)
ans =
    23.603066594891987434787570068504

如果您没有符号工具箱,您仍然可以:

>> g = 0.5772156649015328606065120900824; %// Euler-Mascheroni constant
>> n = 1e10;
>> psi(n+1) + g
ans =
  23.603066594891988