How could I sums up 1/n for n=1 to 10000?

조회 수: 4 (최근 30일)
Wenchen Liu
Wenchen Liu 2022년 9월 23일
댓글: Walter Roberson 2022년 9월 23일
I have a code like this, but I can't run it.
n = 10000; % whatever you want
sum_harm = 0;
for i = 1:n
sum_harm = sum_harm + 1/i;
end
sum_harm
sum_harm = 9.7876

답변 (2개)

Chunru
Chunru 2022년 9월 23일
It can be run as shown below. What problem have you encountered?
n = 10000; % whatever you want
sum_harm = 0;
for i = 1:n
sum_harm = sum_harm + 1/i;
end
sum_harm
sum_harm = 9.7876
  댓글 수: 3
Chunru
Chunru 2022년 9월 23일
There is no variables called "result". You should check "sum_harm" after running your code.
To see the intermediate partial sum, simply remove semicolon at the end of sum statement as shown below:
n = 10; % whatever you want
sum_harm = 0;
for i = 1:n
sum_harm = sum_harm + 1/i % ; suppress display; remove it for display
end
sum_harm = 1
sum_harm = 1.5000
sum_harm = 1.8333
sum_harm = 2.0833
sum_harm = 2.2833
sum_harm = 2.4500
sum_harm = 2.5929
sum_harm = 2.7179
sum_harm = 2.8290
sum_harm = 2.9290
sum_harm
sum_harm = 2.9290
Walter Roberson
Walter Roberson 2022년 9월 23일
n = 1:10000;
result = cumsum(1./n);
result(end)
ans = 9.7876
plot(n, result)

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2022년 9월 23일
Why not try it vectorized:
n = 1 : 10000; % whatever you want
sum_harm = sum(1 ./ n)
sum_harm = 9.7876
What problem did you have in running your code? It ran in MATLAB online. Did you type the m-file name into the command window or click the green run triangle on the tool ribbon? Either should work, but what did you do, if anything? Why do you say you can't run it? Why do you not know how to run the code? Try this link if you don't know how to run your MATLAB program:

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by