Matlab is giving conflicting results, please help.

1 Ansicht (letzte 30 Tage)
AE_Engnr
AE_Engnr am 13 Jun. 2019
Kommentiert: AE_Engnr am 16 Jun. 2019
Using the code below for a cross product, the cross products should be equal but Matlab is saying they aren't.
v = [ 1, 2, 3 ];
r1 = [ 0.3, -0.4, 0.5 ];
r2 = r1 + v;
r1Xf = cross(r1,v)
r2Xf = cross(r2,v)
isequal(r1Xf,r2Xf)
==================
in the command window:
>> isequal(r1Xf,r2Xf)
ans =
logical
0
====================
However, in a little trial I did I am still getting conflicting results:
>> r1Xf
r1Xf =
-2.2000 -0.4000 1.0000
>> r2Xf
r2Xf =
-2.2000 -0.4000 1.0000
>> x=[-2.2, -0.4, 1.0]
x =
-2.2000 -0.4000 1.0000
>> x==r2Xf
ans =
1×3 logical array
0 0 1
>> x==r1Xf
ans =
1×3 logical array
1 0 1
=================
I don't understand why the arrays are all [-2.2, -0.4, 1.0], but Matlab still says they aren't equal?

Akzeptierte Antwort

Stephen23
Stephen23 am 13 Jun. 2019
Bearbeitet: Stephen23 am 13 Jun. 2019
"...but Matlab still says they aren't equal?"
Because they aren't equal.
This is very easy to check (you already used one method, here is another):
>> r1Xf - r2Xf
ans =
-8.8818e-016 4.4409e-016 0
>> x - r1Xf
ans =
0 -1.1102e-016 0
>> x - r2Xf
ans =
-8.8818e-016 3.3307e-016 0
"... the cross products should be equal "
Nope, I don't see any reason to expect them to be equal. Operations on floating point numbers collect floating point error. You need to learn about the limits of floating point arithmetic.
"I don't understand why the arrays are all [-2.2, -0.4, 1.0]..."
Because the operations collect different floating point error for different input values. What you see printed in the command window is the closest representation to 5 or 16 significant digits, depending on your current format setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa's num2strexact and you will see that none of those values really have the exact value -2.2 or -0.4. All you are looking at is a representation of those floating point numbers displayed in the command window, to the precision defined by your format setting. Just because you see -2.2 or -0.4 displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value is displayed by changing the format.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:

Weitere Antworten (0)

Kategorien

Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by