Why does this code, which is written to calculate sin(0) to sin(pi), also calculate sin(1.1*pi) even though the while loop should forbid it?

2 vues (au cours des 30 derniers jours)
clc; clear; i=1; x=0; y(i)=sin(x*pi); while x<1 i=i+1; x=x+0.1; y(i)=sin(x*pi); end y

Réponses (2)

Steven Lord
Steven Lord le 2 Nov 2016
From this article on Cleve's blog (in the section 'Hexadecimal format'):
"Ten steps of length t [t = 0.1] are not precisely the same as one step of length 1. MATLAB is careful to arrange that the last element of the vector 0:0.1:1 is exactly equal to 1, but if you form this vector yourself by repeated additions of 0.1, you will miss hitting the final 1 exactly."
  1 commentaire
Gregory Fernandes
Gregory Fernandes le 2 Nov 2016
Thanks!
I get the correct result (sin(1.1pi) is not calculated) when I alter the code slightly such that it reads as follows:
clc; clear; i=1; x=0; while x<1 y(i)=sin(x*pi); i=i+1; x=x+0.1; end y
Can you help me figure out why ten steps of 0.1 don't get me in trouble with this modified code?

Connectez-vous pour commenter.


Alexandra Harkai
Alexandra Harkai le 2 Nov 2016
Is there a specific reason why you want to use a while loop? This would be much easier/quicker/easier to read is you vectorise it:
y = sin(pi*(0:0.1:1))
  2 commentaires
Gregory Fernandes
Gregory Fernandes le 2 Nov 2016
Thanks so much for the suggestion. I am working through a text that asks us to "generate of a vector containing sin(0)-sin(pi) using the while loop" as a simple exercise aimed at introducing students to logic flow control.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by