This code uses a while loop to determine which value of x can be taken to say that the value of e^-x is approximately equal to zero. In order to do this, a tolerance value has been added (1e-3) so that if the output exceeds the tolerance, the for loop terminates.
For context, this code was given to us to demonstrate how to use a "counter" within a while loop.
I am struggling to understand how the "counter" value works within this code.
1) There seems to be x(counter), yet we have not yet determined what the value of x is equal to. I understand that it is effectively saying x(1) = 0 but surely we need to assign a value to x?
2) Why do we need to rewrite result(counter)= e^-x(counter) inside the while loop, why will the code not work if we simply put result(counter)?
result(counter) = exp(-x(counter))
while result(counter)>tol;
x(counter) = x(counter-1) + 1;
result(counter) = exp(-x(counter))
end
result =
1.0000 0.3679
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
result =
1.0000 0.3679 0.1353
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
result =
1.0000 0.3679 0.1353 0.0498
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
result =
1.0000 0.3679 0.1353 0.0498 0.0183
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
result =
1.0000 0.3679 0.1353 0.0498 0.0183 0.0067
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
result =
1.0000 0.3679 0.1353 0.0498 0.0183 0.0067 0.0025
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
result =
1.0000 0.3679 0.1353 0.0498 0.0183 0.0067 0.0025 0.0009
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>