Help with Homework please Loops are hard

3 ビュー (過去 30 日間)
Hasan
Hasan 2014 年 11 月 1 日
コメント済み: Walter Roberson 2021 年 3 月 9 日
Use a while-end loop in a script file to calculate the sum of the first n terms of the series:
Summation sign on the top n bottom k=1 : ((-1)^k * k^2 +5k)/3^k Show the script file and the two results of n = 10 and n = 20.
WHAT IS THIS I DONT UNDERSTAND LOOPS HELP PLEASE IM BEGGING!!!. x.x

採用された回答

Harry
Harry 2014 年 11 月 1 日
So, in the first case, you have to add 10 numbers together. In the second case, you have to add 20 numbers together. I'm sure you know how to add numbers together, so don't be intimidated by the loop.
In my opinion, the natural way to do this sum is with a "for" loop:
total = 0;
for k=1:n
total = total + ((-1)^k * k^2 +5*k)/3^k;
end
However, you have been told to do this with a "while" loop. Therefore, it is equivalent to write:
total = 0;
k=1;
while k <= n
total = total + ((-1)^k * k^2 +5*k)/3^k;
k = k+1;
end
All you have to do is define "n" as required.
  2 件のコメント
Hasan
Hasan 2014 年 11 月 1 日
So basically all i have to do is say n=1 and n=20 in both cases when i run the code?
Harry
Harry 2014 年 11 月 1 日
編集済み: Harry 2014 年 11 月 1 日
Yes, you should run it with n = 10 and n = 20.
Note that for large n, the term ((-1)^k * k^2 +5*k)/3^k gets very small. Therefore, the answers for n = 10 and n = 20 will look almost the same. If you type "format long g" before running the code, this will make Matlab display more precision so you can see the difference.
As you use Matlab more, you will find that you don't need to use loops for simple sums like this. Instead, your code will normally run much faster if you operate on vectors. In other words, your loop can simply be replaced with this:
k = 1:n;
total = sum(((-1).^k * k.^2 + 5*k)./3.^k);

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

その他の回答 (1 件)

Ralph Lopez
Ralph Lopez 2021 年 3 月 9 日
Programming Requirements : 1. Implement modularization 2. Two user inputs 𝒙 and 𝒏 3. Provide a re-run (try again) program segment 4. Output must be in tabular form that shows that column for no. of terms, approximate value, and approximate estimate error. 5. Show the number of terms needed to satisfy the criterion.
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 3 月 9 日
This does not appear to be an Answer to the question that was asked?

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

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by