In: Computer Science
In class we learned that, if terms added in a series continually decrease in size, the terms will eventually be too small to be stored by MATLAB. When a number is too small to be stored, we learned that such a situation is called underflow; in this case, MATLAB will just store it as 0. We also learned that a program computing such a series can terminate the loop when the next term to be added is equal to 0 (because of underflow).
It also turns out that, when each term is added to the running sum in a series, the next term to be added will eventually be so small in size relative to the running sum, that this next term will not even be picked up by the running sum- even before the terms reach underflow. In other words, even though additional terms are added, the running sum will eventually stop changing - even before underflow for the next term is reached.
In the script below, where indicated, write a segment of script that uses one while loop (not vectors) to approximate sin(3.76) using the series, sin(x) approximately equals Sum i = 0 to n ((-1)^i x^(2i+1))/(2i+1)!, for the largest n possible. In other words, add terms to the series just until running sum stops changing. Furthermore,
i) Store the running sum into variable, runsum.
ii) Note that you will need to keep track of a current running sum (runsum) and the previous sum ( call it sumold), which contains one less term. You will need to compare these in the condition of a while loop, which will terminate once they are the same The final value of runsum will contain up to and include the first term that doesn't change runsum, i.e. when runsum = sumold. Note that you will need to initialize runsum and sumold with different values to start the loop.
iii) Also, define variable, isum, to be a counter that will keep track of the number of terms added. The final value of isum will be the number of terms in the final runsum.
Use only arithmetic operations and no built in functions (nor ^). Use only one for loop.
format long
% write the code for part(a) here
%display final variables
runsum
isum
The MATLAB script for the above problem is:
x = 3.76; % x initialised to 3.76
runsum = 0; % all variables initialised to 0
isum = 0;
sumold = -1; % initialised to -1 so as to pass the while loop
f = 1; % factorial value is initialised to 1
while runsum ~= sumold
sumold = runsum; % store new value in old value
runsum = runsum + ((-1)^isum * x^(2*isum + 1))/f; % update runsum
f = f * (2*isum + 2) * (2*isum + 3); % update factorial value
isum = isum + 1; % isum updated after each iteration
end
disp(runsum)
disp(isum)
The sample of the code is:
The output sample of the code is:
The file name is hidden due to the guidelines. However, if you have any queries in the above code comment down. I will help you out as soon as possible.