Unexpected result linspace function
13 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Nguyen Trung Kien
le 30 Nov 2018
Commenté : Nguyen Trung Kien
le 30 Nov 2018
Today I am working with
linspace
function. I used it as
x = linspace(x1,x2,(x2-x1)/deltax+1)
When I passed the value of x1, x2, deltax as:
x1=0.2;
x2=0.5;
deltax=0.1;
I got the result
x = 0.2 0.35 0.5
I try again with
x = linspace(0.2, 0.5, 4)
the result was as expected:
x = 0.2 0.3 0.4 0.5
I do not know it is a bug or other side effect of linspace function. Please help me to understand this. Because if I try:
x1=0.2;
x2=0.6;
deltax=0.1;
The result was good
x = 0.2 0.3 0.4 0.5 0.6
Thank you in advance for your consideration. The following image is the console command I tried:

0 commentaires
Réponse acceptée
Mark Sherstan
le 30 Nov 2018
It is due to round off error. Linspace documentation states the following regarding the fuction: If n is not an integer, linspace rounds down and returns floor(n) points. The number is really close to 4 but not 4 so linspace is rounding the number down to 3 or "flooring" it. The other case is exactly 5 and you dont have that issue. Try the following in MATLAB and you will see:
x1=0.2;
x2=0.5;
deltax=0.1;
x = (x2-x1)/deltax+1
x == 4
>> False
x1=0.2;
x2=0.6;
deltax=0.1;
x = (x2-x1)/deltax+1
x == 5
>> True
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!