Matlab equality problem. Please help.

11 Ansichten (letzte 30 Tage)
Jenny Chen
Jenny Chen am 3 Okt. 2018
Bearbeitet: Stephen23 am 4 Okt. 2018
Hi, this is my code.
theta(k) = 45
l = x.*cosd(theta(k))+y.*sind(theta(k));
l(1,1) == l(3,3);
x(1,1)*cosd(45)+ y(1,1)*sind(45) == x(3,3)*cosd(45)+ y(3,3)*sind(45);
x(1,1)+ y(1,1)==x(3,3)+ y(3,3);
However, matlab it saying
l(1,1) == l(3,3)
is false,
x(1,1)*cosd(45)+ y(1,1)*sind(45) == x(3,3)*cosd(45)+ y(3,3)*sind(45)
is false, and
x(1,1)+ y(1,1)==x(3,3)+ y(3,3)
is true. I am wondering why because I believe l(1,1) == l(3,3) is true.
  2 Kommentare
Rik
Rik am 3 Okt. 2018
Your code is not self-contained (i.e. we cannot run it independently of the code you have before this), and I don't understand what you mean with your code/notation.
A wild guess would be that you are checking equality on a non-integer data type, which means you might be encountering float rounding errors. If you run the code below, you can clearly see that 1.0000 does not equal 1.0000
a=1+eps*2;%very close to 1
b=sqrt(a);b=b^2;%do an operation and reverse it
clc,isequal(a,b)
disp(a)
disp(b)
Jenny Chen
Jenny Chen am 3 Okt. 2018
Bearbeitet: Stephen23 am 4 Okt. 2018
Hello, sorry, this should be enough to run.
theta = [45];
[Pr,Pc] = size(P);
nt = length(theta);
x = zeros(Pr,Pc);
y = zeros(Pr,Pc);
for i = 1:Pr
for j = 1:Pc
x(i,j) = j - 1;
y(i,j) = Pr - i;
end
end
for k = 1:nt
l = x.*cosd(theta(k))+y.*sind(theta(k));
l(1,1) == l(3,3)
x(1,1)*cosd(45)+ y(1,1)*sind(45) == x(3,3)*cosd(45)+ y(3,3)*sind(45)
x(1,1)+ y(1,1)==x(3,3)+ y(3,3)
end

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 4 Okt. 2018
Bearbeitet: Stephen23 am 4 Okt. 2018
You have to learn about floating point numbers, and why you should not test them for equality like that. Always compare the absolute difference against a tolerance, like this:
abs(A-B)<tol
Start by reading these:
This is worth reading as well:
To see the "real" value download James Tursa's FEX submission:
"I am wondering why because I believe l(1,1) == l(3,3) is true"
If you use num2strExact on both of those values, you will find that they are not the same, and MATLAB's output is correct. That is why you should compare the absolute difference against a tolerance.

Weitere Antworten (1)

Image Analyst
Image Analyst am 3 Okt. 2018

Kategorien

Mehr zu Linear Algebra finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by