How to sum only the positive elements in a series?

I was asked to write a program to calculate only the positive elements of a series until the sum has reached the required value.
A picture for the series:
I have managed to write a code but the code repeats the loop infinite times until I force it to stop.
sum = 0.0;
n = 0;
disp(' n Sum');
while sum < 4
n = n + 1;
sum = sum + f(n);
if sum > 0;
sum = sum + f(n);
disp([n sum]);
else
disp('skip');
end
end
f(n) in the code represent this:
function y = f(x)
y = ((-1)^(x+1))*(1/x);
Im not confident about the 'else' part of the loop.
Any help is appreciated.

 채택된 답변

Roger Stafford
Roger Stafford 2014년 2월 27일

1 개 추천

Sultan, I think you are interpreting your instructions incorrectly. It says, "calculate only the positive elements of a series until the sum has reached the required value" which I think means to sum only the positive elements. You are summing every number. The test you make is useless because that sum, even if it includes negative values, can never itself be negative. Just keep adding the numbers which are positive and skip over the negative ones until the sum of the positives reaches or exceeds the desired value.

추가 답변 (3개)

Walter Roberson
Walter Roberson 2014년 2월 27일

0 개 추천

what is f(n) exactly? If f(1) = (-1)^(n+1)*1/n then you are going to get negative values and you are adding those negative values into "sum" before you are testing to find out if the term was negative.
Note: do not use "sum" as the name of a variable or you will run into problems.
Jos (10584)
Jos (10584) 2014년 2월 27일
This piece of pseudocode might get you started:
while CurrentSum < maxixumSum
n = n + 1
CurrentValue = (-1^n)/n
if CurrentValue > 0
% … etcetera
Sultan
Sultan 2014년 2월 27일

0 개 추천

Thanks guys, Ive managed to solve it, thanks to your hints.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2014년 2월 27일

댓글:

2014년 2월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by