简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM