1 - 1 = -0 on Matlab why? How to fix that?

조회 수: 1 (최근 30일)
Steven Shaaya
Steven Shaaya 2021년 11월 30일
댓글: Steven Shaaya 2021년 11월 30일
I am working with a matrix that has two columns.
I writing a code to do columns 1 minus columns 2. And the matlab display the result which is all fine.
However, some rows have the same values; for example;
x = [1 2 3; 2 2 5; 3 2 6]
y = [ 4 2 6; 1 2 7; 5 2 3]
w=x(:,2)-y(:,2)
% now on this case I get
w =
0
0
0
% however, the code that I am working with has one row1 column 1 that has value of 1.0700 and row1 column 2 has value 1.0700
now this give an output of -0.0000
I was wondering if there is a solution for this issue.
Now, I am doing some operation to column 2 and my guess is that there is some rounding issue.
I do look at both columns before I do the subtraction between columns 1 & 2 and I see that both values are 1.0700 so where does this rounding proplem is coming from.
  댓글 수: 9
Steven Shaaya
Steven Shaaya 2021년 11월 30일
Can I make the matlab round the values of culmun 2 to four decimal places, so that the value of column 2 will be exactly 1.0700 and I don't have to worry about 10^-16 rounding issue anymore? So I can round the values before using "If statement".
I know how to round values in matlab when using fprintf function
but I am not sure how to do that for a value; for example, say
X = 0.90000000001 % how to round this value to four decimal places without using fprintf
Thank you all
Steven Shaaya
Steven Shaaya 2021년 11월 30일
Thank you all again for your help.
I solved the issue by using "round" function. I did work and -0.0000 is not there anymore!

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

답변 (1개)

Walter Roberson
Walter Roberson 2021년 11월 30일
num2hex(x(1,1:2))
You will find that they have slightly different internal representations.
  댓글 수: 3
Walter Roberson
Walter Roberson 2021년 11월 30일
Do the numbers show up with the same hex representation, or with different hex representations?
If they are different hex representations then that proves that they are not the same number.
I suggest that you use https://www.mathworks.com/matlabcentral/fileexchange/22239-num2strexact-exact-version-of-num2str to display the exact value of each of the values.
If you have Mac then you can get away with something like
fprintf('%.999g\n', x(1,1:2))
Historically fprintf() produced incorrect outputs on Windows; I do not know if that has been changed on Windows.
Steven Shaaya
Steven Shaaya 2021년 11월 30일
No, they do not have the same values.
there is a difference of 10^-16.

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

카테고리

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

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by