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

1 view (last 30 days)
Steven Shaaya
Steven Shaaya on 30 Nov 2021
Commented: Steven Shaaya on 30 Nov 2021
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 Comments
Steven Shaaya
Steven Shaaya on 30 Nov 2021
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 on 30 Nov 2021
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!

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 30 Nov 2021
num2hex(x(1,1:2))
You will find that they have slightly different internal representations.
  3 Comments
Walter Roberson
Walter Roberson on 30 Nov 2021
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 on 30 Nov 2021
No, they do not have the same values.
there is a difference of 10^-16.

Sign in to comment.

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!