Latitude/Longitude -> X/Y, X/Y -> Latitude/Longitude
<p>I found some code for converting latitude/longitude to pixels on a given image and vice versa. I ported it to JavaScript but am getting incorrect return values on the latitude. I tested the original, unmodified code and it gives the same inaccuracies. Below is the code with the values it returns.</p>

<pre><code>function degrees_pixels(latitude, longitude, width, height) {
    return {
        x:  ( longitude + 180 ) * ( width / 360 ),
        y:  ( height / 2 ) - ( width * Math.log(Math.tan(( Math.PI / 4 ) + ( ( latitude * Math.PI / 180 ) / 2 )) ) / ( 2 * Math.PI ) )
    };
};

function pixels_degrees(pixel_x, pixel_y, width, height) {
    return {
        latitude:   ( Math.exp( -( pixel_y - ( height / 2 ) ) / width * ( 2 * Math.PI )) - Math.tan(( Math.PI / 4 )) * 2 ) / ( Math.PI / 180 ),
        longitude:  ( pixel_x - ( width / 2 ) ) / ( width / 360 )
    };
};

var tmp1 = degrees_pixels(40.7127, -74.0059, 256, 256);
console.log(tmp1); // Prints {"x":75.3735822222222,"y":96.2511781695169} which is correct
console.log(pixels_degrees(tmp1.x, tmp1.y, 256, 256)); // Prints {"latitude":10.3018054035438,"longitude":-74.0059} of which the latitude is incorrect
</code></pre>

<p>I have tried fixing it myself but I am struggling with the math. I am not really sure why it is off the way it is.</p>