why this logical expression is wrong?

1 Ansicht (letzte 30 Tage)
mohammad fallah
mohammad fallah am 18 Jul. 2019
Kommentiert: Peter Jarosi am 19 Jul. 2019
Hi,
why this statment is wrong,
>> sind(30)==0.5
ans =
0
  4 Kommentare
Walter Roberson
Walter Roberson am 18 Jul. 2019
I seem to remember seeing a sind bug in the bug reports a couple of releases ago, but I cannot find that information now.
Peter Jarosi
Peter Jarosi am 18 Jul. 2019
I think it's not a bug, because it depends on the method of approximation. That's an interesting question how developers of sind() function fixed sind(30). Whether there is an if statement in the code of sind() in order to set sind(30) exactly 1/2. :-)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Peter Jarosi
Peter Jarosi am 18 Jul. 2019
Bearbeitet: Peter Jarosi am 18 Jul. 2019
because of the accuracy problem of a floating-point system
>> format longE
>> sind(30)
ans =
4.999999999999999e-01
Never, ever compare two floating-point numbers with == operand!
See also:
  11 Kommentare
Peter Jarosi
Peter Jarosi am 18 Jul. 2019
I voted your question. It's a million dollar question, and the problem is general, not Matlab's fault.
Walter Roberson
Walter Roberson am 18 Jul. 2019
The result of sind(30) should be exactly 1/2, but it appears that in some older releases it was not exactly that.
It is generally better to not compare for floating point equality except when you know that the exact bit-pattern occurs somewhere. For example, it is fair to test
A = min(B);
B == A
because you know that A will be a bit-for-bit copy of one of the values that is in B. (Well, except for some obscure cases involving non-default nan values... and in those cases, nan == nan is always false anyhow.)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Steven Lord
Steven Lord am 19 Jul. 2019
This is a bug. See Bug Report 1839169.
  1 Kommentar
Peter Jarosi
Peter Jarosi am 19 Jul. 2019
How did you fix it? Did you use a better approximation method (for instance longer Taylor series) or just put an if statement in the code of function sind()? :-)
(I'm joking)

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by