优化MATLAB代码 [英] Optimizing MATLAB code
问题描述
此代码需要非常长的时间才能运行(超过10分钟).有什么方法可以优化它,使其在不到一分钟的时间内完成?
This code takes an extremely long time to run (more than 10 minutes). Is there any way in which I can optimize it so that it finishes in less than one minute?
clear all;
for i = 1:1000000
harmonicsum = 0;
lhs = 0;
for j = 1:i
% compute harmonic sum
harmonicsum = harmonicsum + 1/j;
% find sum of factors
if (mod(i,j)==0)
lhs = lhs + j;
end
end
%define right hand side (rhs) of Riemann Hypothesis
rhs = harmonicsum + log(harmonicsum) * exp(harmonicsum);
if lhs > rhs
disp('Hypothesis violated')
end
end
推荐答案
@b3 has a great vectorization of rhs
.
不过有一个错字,需要使用times
而不是mtimes
:
One typo though, needs to use times
and not mtimes
:
harmonicsum = cumsum(1 ./ (1:1e6));
rhs = harmonicsum + log(harmonicsum) .* exp(harmonicsum);
对于lhs
,我大致根据Eratosthenes的筛子提出以下建议:
For lhs
, I propose the following, loosely based on Eratosthenes' Sieve:
lhs = 1 + [1:1e6];
lhs(1) = 1;
for iii = 2:numel(lhs)/2
lhs(2*iii:iii:end) = lhs(2*iii:iii:end) + iii;
end;
执行时间仅为2.45秒(针对问题的这一半).包括计算rhs
和find
在内的总计不到3秒.
Execution time is just 2.45 seconds (for this half of the problem). Total including calculation of rhs
and find
is under 3 seconds.
我目前正在运行其他版本,以确保结果相同.
I'm currently running the other version to make sure that the results are equal.
发现一个带有lhs(1)
的错误并将其特殊化(这是特殊情况,这是唯一的自然数,其中1和N不是不同的因素)
found a bug with lhs(1)
and special-cased it (it is a special case, the only natural number where 1 and N aren't distinct factors)
这篇关于优化MATLAB代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!