Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

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

I have a problem with matlab. I need to sum math serie 1/x from 1 to 1E10. I have some code in Matlab which contains loop - first loop step is ok very fast), but on second step in loop it slows down and Matlab is almost freezed, so I cannot calculate this in appropriate time.

Can you help me with this?

For smaller range it works OK (for example 1E06), but I need to calculate for the whole range. I have tried to separate to smaller range, but there is still loop and matlab is very slowed.

It looks like a problem with matlab and for loop, which slows down. After first loop step the RAM is full but for the second loop step the RAM is still full so it slows down. I don′t know why the Matlab does not free the RAM.

Thank you for any help!

Vladimir

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want to obtain the 1e10-th harmonic number. In the Symbolic Toolbox there is a function for that, called harmonic, and it's very fast:

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

The reason why it's so fast is that the harmonic function exploits the relationship between harmonic numbers, the Euler-Mascheroni constant and the digamma function:

enter image description here
where "psi" is the digamma function, Hn is the n-th harmonic number, and "gamma" is the Euler-Mascheroni constant. So you could also use

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

If you don't have the Symbolic Toolbox, you can still do:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...