I want to compute the sum of the following series in Matlab:

I am using this MATLAB function:
>> syms i;
>> S = symsum((0.5^i*sin(i))/i^2, i, 0, Inf)
The problem is that I want to stop adding terms when the sum stops changing. For example, condition of when to stop might be that difference between sum at step i step and sum at step i+1 is not larger than some user-defined tolerance 10^-8. How can I include this condition in the above sum computation?
I would personally not use the Symbolic Math Toolbox and prefer to use a simple loop instead. Specifically, I would do this numerically and incrementally add terms to the series until the condition you speak of is satisfied. BTW, your sum starts at i=0, but when i=0, the summation is undefined (you have a 0/0 undefined division result). I assume you meant to start at i=1 instead.
Something like this comes to mind:
s = 0;
s_before = realmax;
tol = 1e-8;
ii = 0;
while (abs(s_before - s) >= tol)
ii = ii + 1;
s_before = s;
s = s + ((0.5^ii)*sin(ii))/(ii^2);
end
The first four lines of code are used for setup. s contains the final sum and s_before contains the sum from the previous iteration. tol defines a tolerance (your example is 1e-8) which measures the difference between successive iterations. ii is a counter variable which is the i variable in the sum formula. Note that I initialize this to 0, but on the first iteration, this will get set to 1. I also choose to use ii instead of i as i is reserved for the complex variable instead.
Next, we use a while loop and we will keep looping as long as the difference between successive iterations is greater than the tolerance. We save the previous iteration's sum, then compute the next term in the series and accumulate this in the total sum. We also make sure to increment the counter variable. This will quit when the difference between successive iterations is less than a certain amount.
I get this for the total number of iterations and the sum once I run this code:
>> format long g;
>> s
s =
0.475415855580831
>> ii
ii =
18
Doing format long g; at the beginning will allow us to show more digits of precision. By default, MATLAB only shows up to 4 decimal places. The result tells us that this required 18 terms in your summation for it to "stop changing".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With