Help with Homework please Loops are hard

13 次查看(过去 30 天)
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.

类别

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