Search code examples
javascripttrigonometrydegreesradians

Converting from degrees to radians and back leaves a very small leftover


So I have the following javascript code:

function dosine(){
    var num = document.getElementById('num').value;
    console.log(num);
    num = (num*Math.PI)/180;
    num = Math.sin(num);
    numinverse = Math.asin(num);
    num = num * (180/Math.PI);
    numinverse = numinverse * (180/Math.PI);
    document.getElementById('resultsine').innerHTML = "Sine: " + num.toString();
    document.getElementById('resultinverse').innerHTML = "Inverse Sine: " + numinverse.toString();
}

When I run this code and put in any number (in this case I used 64 for testing) the numinverse returns 64.00000000000001, I was just wondering why this is. I could obviously solve this by using toFixed, but I was wondering why this happened in the first place.


Solution

  • This could be the same why 0.1 + 0.2 ≠ 0.3

    The value is a floating point number and doesn't behave very accurately. In your case you could also create some hash tables mapping integer degrees values to radians but yet it wouldn't cover the whole spectrum.