In a simple geometric program written in Javascript and Canvas, when I set the angle to 270° (1½π), I expected the Math.cos(θ) to go to zero. The vector is straight down from the center, there's no x distance on a cartesian grid. Instead, I get this:
demo_angle = 270
ang = demo_angle * Math.PI / 180
x = Math.cos(ang)
console.log(x)
> -1.836909530733566e-16
To see the output of the math functions, view the console. The source code is visible (in coffeescript) one level up in the URL.
I've had to define in my code "Any number whose absolute value is smaller than 1e-15 should be considered zero," but that's really unsatisfying. Needless to say, when I try doing math with the x
value that small, especially since I'm trying to use x
as the denominator in a slope calculation and then doing some quadratic manipulations, I eventually come up with figures that exceed Number.MAX_VALUE (or Number.MIN_VALUE).
I know floating point mathematics is, at the assembly language level, something of a dark art, but results like this just seem weirder than is acceptable. Any hints on what I should do?