Question

Hey i've made a rotation function in Javascript for rotating some 2D vector(point).

The Y output of the function works as expected, however the X value is outputting some crazy number, can anyone point out the floor in my logic?

Vector2.prototype.rotate = function(degrees){

    var angle = degrees * TO_RADIANS; //Convert to radians.
    var x =  (this.getX() * Math.cos(angle)) - (this.getY() * Math.sin(angle));
    var y = (this.getX() * Math.sin(angle)) + (this.getY() * Math.cos(angle));
    return new Vector2(x,y);
};

Inputting Vector(1,0) into this function with a rotation of 90 degrees outputs 6.someDecimalPlaces e-17; which is obviously incorrect.

The outputted Y value however works as expected and returns 1.

Thanks in advance

Was it helpful?

Solution

The "6.someDecimalPlaces e-17" you're seeing is due to Javascript's handling of floating point numbers. What you're seeing is a rounding error in converting back from binary floating point to decimal. There's no easy fix for this although there are libraries that attempt to overcome the problem.

If you want rounded numbers for pixel perfect CSS manupilation you're best bet is to round the numbers coming out of this function or cast them to integer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top