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

9 次查看(过去 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