1 - 1 = -0 on Matlab why? How to fix that?
1 次查看(过去 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.
回答(1 个)
Walter Roberson
2021-11-30
num2hex(x(1,1:2))
You will find that they have slightly different internal representations.
3 个评论
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!