Confusion Concerning Numerical Equation
drug
drug2004 at bk.ru
Sat Nov 16 10:17:12 UTC 2019
16.11.2019 13:01, Avery Stupidman пишет:
> Hello,
>
> I have a function "angle" that returns the angle (in degrees) of a right
> triangle given the length of the its lengths as type "real". It works,
> but when trying to test the equality of the angle with the seemingly
> identical value, I'm informed that the two are not equal. Thus, when
> angleDeg(sqrt(3.0)/2.0, 1.5) returns 60, the comparison
> "angleDeg(sqrt(3.0)/2.0, 1.5) == 60" resolves to false.
>
> I'm most likely stupid and sleep deprived, but if I may have some
> elucidation, I'd be very grateful.
>
> Some code:
>
> real angleDeg(real x, real y)
> {
> import std.math : PI, abs, atan2, sgn;
>
> auto angle = atan2(y, x);
>
> // Simplify angle if vector resides in quadrants II or III
> if (x < 0)
> {
> angle = (PI - abs(angle)) * sgn(angle);
> }
>
> return angle * 180 / PI;
> }
>
> import std.math : sqrt;
>
> assert(angleDeg(sqrt(3.0)/2.0, 1.5) == 60.0); // Fails
In general you shouldn't compare floating point values for equality
because of their nature, you can use something like approxEqual
https://dlang.org/library/std/math/approx_equal.html
P.S. see also https://floating-point-gui.de/errors/comparison/
More information about the Digitalmars-d-learn
mailing list