Simple assertion giving incorrect result?
Afficher commentaires plus anciens
Here's a simple version of something that's arising in some code. The student needs to use vpasolve. The reference solution is this:
syms x
x1 = vpasolve(exp(abs(0.1*x))+2*sin(x)==0,-2)
This reference solution returns a value:
x1 =
-2.4487454187687442582374719820392
When the student puts in a different seed value for vpasolve:
syms x
x1 = vpasolve(exp(abs(0.1*x))+2*sin(x)==0,-3)
The learner solution returns the same value as the reference solution:
x1 =
-2.4487454187687442582374719820392
However doing a simple assertion test of whether these two variables are equal fails. Why would this happen?
Réponses (2)
Justin Wyss-Gallifent
le 11 Juil 2020
2 commentaires
John D'Errico
le 11 Juil 2020
Sorrry, but this is still wrong. The answer is to NEVER assume a floating point number is known identically. The rsult from vpasolve is still a floating point number. It just has more digits.
The same statement of mine is true, even for double precision numbers. NEVER assume they will be identical. Testing for identically equal floating point numbers will result in failure, and then you will be back here, wondering why you have a problem.
When you test for same-ness of two floating point numbers, use a tolerance. Test to see if the absolute value of the difference is sufficiently small.
Walter Roberson
le 11 Juil 2020
Modifié(e) : Walter Roberson
le 11 Juil 2020
assessVariableEqual() is part of Grader. It uses a tolerance, but only for numeric items (symbolic items are not considered numeric for this purpose.)
Walter Roberson
le 11 Juil 2020
0 votes
Symbolic floating point values have some guard digits that are not displayed when you output the number
2 commentaires
Justin Wyss-Gallifent
le 11 Juil 2020
Walter Roberson
le 11 Juil 2020
consider that if you have
A = 1
B = A*(1-eps)
then no matter which numeric "format" statement you choose, A and B will display the same (well, other than format hex). They will not compare equal because floating point has no sense of tolerance. assessVariableEqual is not part of MATLAB, it is part of the Grader tool.
Perhaps you are saying that assessVariableEqual has no sense of tolerance for symbolic values, but any tolerance it does have is part the grader. MATLAB itself has no approximately_equal operator, just ismembertol function call.
Catégories
En savoir plus sur Number Theory dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!