Issue with small floating point numbers

Zardoz luis.panadero at gmail.com
Thu May 13 05:50:00 UTC 2021


On Thursday, 13 May 2021 at 03:03:37 UTC, Tim wrote:
> Hello all,
>
> I have this piece of code
> ```D
> /**
> Rotate a 2D array (Vector) by phi radians
>
> Params:
>     vec = 2D Vector to rotate
>     phi = Degree with which to rotate the Vector in radians
>
> Returns:
>     Rotated 2D array (Vector)
>
> Example:
>
> */
> pragma(inline, true)
> Point2 rotate2D(in Point2 vec, in float phi) pure nothrow {
>     double x = (vec[0]*cos(phi)) - (vec[1]*sin(phi));
>     double y = (vec[0]*sin(phi)) + (vec[1]*cos(phi));
>     return [x, y];
> }
>
> unittest{
>     auto p = rotate2D([0.0, 10.0], PI_2);
>     assert(p == [-10.0, 0.0]);
> }
> ```
>
> When I run the unittest, I get ```[-10, -4.37114e-07]``` back, 
> which is obviously wrong. Any idea as to why it's not making 
> the y-axis zero? Is it a rounding issue with the types I'm 
> using?
>
> Thanks in advance

You should try to use isClose to compare for floats equality : 
https://dlang.org/phobos/std_math.html#.isClose

Float arithmetic isn't exact, and could give unexpected results 
like 0.1f + 0.2f != 0.3f


More information about the Digitalmars-d-learn mailing list