while loop to count partail sum of series

2 visualizaciones (últimos 30 días)
Arkadius882
Arkadius882 el 16 de Mayo de 2022
Comentada: Torsten el 16 de Mayo de 2022
Hello,
I'm having problems making while loop to count partial sum (110 iterations) of this series: 1/i*(i+1). There is antoher condition that counting precision must be 1e-4. So the loops breaks when all iterations are done or the precision is achieved. Unfotunetely I'm new to MATLAB and haven't ever done series using while only using for.
Here's what I managed to do, as you can see I haven't done antyhing regarding precision since I don't how to do it and the loop is infinite becasue I don't know to make a proper condiiton to break.
i=1; N=110; x=0;
while 1
x1=1/(i*(i+1));
x=x+x1
if i>=N
break
end
end
disp(x)

Respuesta aceptada

Image Analyst
Image Analyst el 16 de Mayo de 2022
Editada: Image Analyst el 16 de Mayo de 2022
Two problems.
  1. You forgot to increment your loop counter, the (badly-named) i.
  2. You forgot to index x so you're just overwriting it every time.
The fix:
N = 110; % Max iterations.
x = zeros(1, N);
x(1) = 1 / (1 * 2);
loopCounter = 2;
while loopCounter <= N
thisTerm = 1 / (loopCounter * (loopCounter+1));
x(loopCounter) = x(loopCounter - 1) + thisTerm;
loopCounter = loopCounter + 1;
end
plot(x, 'b-', 'LineWidth', 2);
grid on;
xlabel('Iteration Number')
ylabel('x, partial sum')
  2 comentarios
Torsten
Torsten el 16 de Mayo de 2022
Editada: Torsten el 16 de Mayo de 2022
x(1) = 1 / (1 * 2);
instead of
x(1) = 1 / (1 + 2);
And
x = zeros(1, N);
must be done before setting
x(1) = 1 / (1 * 2);
Image Analyst
Image Analyst el 16 de Mayo de 2022
Thanks @Torsten for catching those problems. 🙂 I've corrected them in my initial answer.

Iniciar sesión para comentar.

Más respuestas (1)

Torsten
Torsten el 16 de Mayo de 2022
sum_{i=1}^{i=N} 1/(i*(i+1)) = 1 - 1/(N+1)
No need for such a difficult while construction with precision estimate.
  2 comentarios
Arkadius882
Arkadius882 el 16 de Mayo de 2022
The problem is that it needs to be with while loop because that is an academic task :/
Torsten
Torsten el 16 de Mayo de 2022
Then use Image Analyst's solution.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by