フィルターのクリア

Finding the sum to n of 1/2^n

7 ビュー (過去 30 日間)
Thomas
Thomas 2022 年 10 月 12 日
編集済み: Davide Masiello 2022 年 10 月 12 日
I'm trying to right a code which will output the sum of the series 1/2^n.
Ive used a for loop to iterate n from 1 to 20 for this example
My code keeps outputting 1/2^20 as the answer, instead of 1/2 + 1/2^2 + 1/2^3 ... +1/2^20
Here is my code
n = 0;
for n = 1:20
b = 1./(2.^n);
end
Sn = sum(b);
disp(Sn)
What am i doing wrong?

回答 (2 件)

Davide Masiello
Davide Masiello 2022 年 10 月 12 日
You haven't indexed the loop variable
for n = 1:20
b(n) = 1./(2.^n);
end
Sn = sum(b);
disp(Sn)
1.0000
You can also do it without loop
n = 1:20;
b = sum(1./(2.^n))
b = 1.0000
  1 件のコメント
Davide Masiello
Davide Masiello 2022 年 10 月 12 日
編集済み: Davide Masiello 2022 年 10 月 12 日
Of course, if you need the series to start from n=0, just replace n = 1:20 with n = 0:20. That also means you can't use n as loop iteration index, so you change to
n = 0:20;
for i = 1:length(n)
b(i) = 1./(2.^n(i));
end
Sn = sum(b);
disp(Sn)
2.0000

サインインしてコメントする。


Torsten
Torsten 2022 年 10 月 12 日
編集済み: Torsten 2022 年 10 月 12 日
format long
n = 1:20;
b = 1./2.^n;
Sn = sum(b)
Sn =
0.999999046325684

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by