'Decimal.js sin() function returns incorrect result
I have a javascript program that looks like this:
function dosine(){
var num = new Decimal(document.getElementById('num').value);
if(document.getElementById('degrad').value == "degrees"){
num = (num*Math.PI)/180;
console.log(num);
}
num = Decimal.sin(num);
console.log(num.toString());
numinverse = Decimal.asin(num);
if(document.getElementById('degrad').value == "degrees"){
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();
}
In my program, I am now using Degrees.sin and Degrees.asin because of floating-point weirdness with the Math library, but when I get the sin output for 64 I get 51.49710550442818, but on my physical calculator I get 0.920026038197 0.8987940463. Am I using this library wrong, or is my code just not good? I am pretty new to javascript so advice would be very much appreciated. Thanks!
Solution 1:[1]
This has nothing to do with Decimal. You convert num to radians, then you take a sine of it. Finally you convert the result of the sine (which should be a proportion from 0 to 1, not an angle!) from radians to degrees, which makes no sense - it's like converting weight from feet into metres.
This could be avoided by using better naming conventions, using variable names that make sure you know what the variable contains. num is not very semantic - all it tells you is that it has a number in it. Consider angle_in_degrees, angle_in_radians and sine. Then it would be immediately obvious that this is not what you want:
angle_in_radians = Decimal.sin(angle_in_radians) // result is a sine ratio, not an angle!
angle_in_degrees = angle_in_radians * (180 / Math.PI); // good operation on bad data
Another big point is that your code does not stay in Decimal. JavaScript cannot override the default operations, so you have to use Decimal methods to calculate, not +, * and /. Note this:
Decimal(1) + 3 // incorrect
// => "13"
Decimal(1).add(3).toNumber() // correct
// => 4
Finally, unless you are dealing with financial systems, the floating point error is usually negligible; moreover, the result of sine function is irrational, so it can't be represented in Decimal any more correctly than in floating point anyway. Unless you have a use case that makes Decimal.js necessary, just use the normal numbers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
