# Bug in trig functions

I might be missing something but I think there’s a bug in the Basics module `sin` and `cos` functions.

``````> pi
3.141592653589793 : Float
> sin pi
1.2246467991473532e-16 : Float -- should be zero
> cos pi
-1 : Float
> sin 0
0 : Float
> cos 0
1 : Float
> sin (pi/2)
1 : Float
> cos (pi/2)
6.123233995736766e-17 : Float -- should be 0
> sin (pi*2)
-2.4492935982947064e-16 : Float -- should be 0
> cos (pi*2)
1 : Float
``````

any ideas what is going on?

Notice the `e-16` at the end, meaning that you’re not getting 1.22, you’re getting 1.22 divided by ten to the sixteenth power. Which is very small, but not zero.

This is how floating point numbers work, for better or worse. I think it has to do with the fact the `pi` is not exactly π. This is the same answer returned by the JavaScript expression `Math.sin(Math.PI)`.

If you’re working with floating point numbers in elm-test, there are dedicated functions for expecting a value to be within a certain tolerance.

I guess I just have to remember to run `floor` on those values to get 0.

Using `floor` won’t work either, since in your

``````> sin (pi*2)
-2.4492935982947064e-16 : Float
``````

example, using `floor` will give you -1, not 0! You could use `round`, but depending on exactly what you’re doing there will almost certainly be a better solution. If you’re testing something, test within a tolerance as @mgold mentions, or if you just want to display the result in ‘nice’ way then try a dedicated number formatting package; `myrho/elm-round` looks pretty nice.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.