Help with Homework please Loops are hard
조회 수: 5 (최근 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
댓글 수: 0
채택된 답변
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
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
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!