Unexpected result linspace function

13 Ansichten (letzte 30 Tage)
Nguyen Trung Kien
Nguyen Trung Kien am 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:
Capture.PNG

Akzeptierte Antwort

Mark Sherstan
Mark Sherstan am 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
  1 Kommentar
Nguyen Trung Kien
Nguyen Trung Kien am 30 Nov. 2018
Thank you so much for your explaination. This helped me to understand and not confuse more.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by