0

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.

CoderMan
  • 37
  • 8
  • 2
    Here you go: https://modernweb.com/what-every-javascript-developer-should-know-about-floating-points/ – Pellay Apr 06 '22 at 11:47
  • 1
    This is because the float aritmetic in javasctipt is fcuked up. For example - check what's the result of `0.1 + 0.2` – pbialy Apr 06 '22 at 11:47
  • You can combat this with [decimal.js](https://mikemcl.github.io/decimal.js/) – Peter Krebs Apr 06 '22 at 11:50
  • I tried using decimal.js, and it returned the same thing, am I using it wrong? – CoderMan Apr 06 '22 at 12:09
  • actually wait I got it right nevermind – CoderMan Apr 06 '22 at 12:29
  • If you wanna nice clear demonstration of just how messed up floating point is in JS, try this... Open the console and type 3 * 0.3 (the answer should be automatically calculated underneath without pressing return). Then just keep pressing 3 and watch the results change. You'll notice very inconsistent results. It will eventually evaluate a 1 as you approach 16 3's – Pellay Apr 06 '22 at 12:46
  • that is very weird, I just did that and got very inconsistent results – CoderMan Apr 06 '22 at 12:56
  • also, in my program I am now using Degrees.sin and Degrees.asin, but when I get the sin output for 64 I get 51.49710550442818, but on my physical calculator I get 0.920026038197, so I don't know what's going on there. – CoderMan Apr 06 '22 at 12:57
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Peter O. Apr 06 '22 at 15:49

1 Answers1

1

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.

Diego D
  • 6,156
  • 2
  • 17
  • 30