Possible Duplicate:
Is JavaScript’s Math broken?
So I was working on a js library to work with 3 dimensional vectors and I stumbled upon a very small precision problem. Ok firstly, see the code below:
var a = new vec3(1, 0, 0);
var b = new vec3(1, 1, 0).normalize();
There I'm creating 2 vectors at exactly 45° degrees from one another (I have omitted the vec3
constructor as I just do standard math stuff there)
Now you people know that the dot product of 2 3D vectors yields their magnitudes and the cosine of the angle multiplied. But when I do this:
alert(180 / Math.PI * Math.acos(a.dot(b)));
I get 45.00000000000001
I understand that this is a very, very small difference but this would prevent me from being able to check if the angle between 2 vectors is 45° in case I didn't know that beforehand, since Math.acos(a.dot(b)) == Math.cos(Math.PI / 180 * 45)
would result in false
But here is a funny thing, if I change my vectors to this:
var y = new vec3(Math.sqrt(2), Math.sqrt(2), 0).normalize();
var x = new vec3(Math.sqrt(2), 0, 0).normalize();
And then do the same calculation as above, it gives me exactly 45.
Now I'm aware that I can round that 45.00000000000001
, but since I'm totally noob to subjects regarding how mathematical functions are implemented on lower levels I got really curious about what factors could cause two calculations that should give exactly the same value to result in slight different things.