Unexpected result linspace function

조회 수: 13 (최근 30일)
Nguyen Trung Kien
Nguyen Trung Kien 2018년 11월 30일
댓글: Nguyen Trung Kien 2018년 11월 30일
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

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by