Why does changing the sum order returns a different result ?
In mathematics, addition is associative in nature. The associative law states that the result of summation remains the same irrespective of the order of addends. This is true for all programming languages when the addends are integers. However, there is a slight difference in behavior when the addends are floating-point numbers.
Most of the CPUs in use today use the IEEE 754 binary floating-point standard, which introduces inaccuracies when decimal numbers are stored as binary values. The change in sum result is observed because when we change the order the intermediate value stored in the memory also changes and therefore the end result also changes. Let us consider the below example that shows how different outputs are obtained whenever the order is changed.
a+b+c 21.540000000000003 b+c+a 21.54 b+a+c 21.540000000000003
The package can be installed using the below npm command.
npm install js-big-decimal
Approach 1: The package contains an inbuilt add() method which takes two string arguments, adds them, and returns the rounded result. This can be used to correctly add multiple numbers.
a = 10.54 b = 9.99 c = 1.01 a+b+c = 21.54 b+c+a = 21.54 b+a+c = 21.54
Approach 2: Another approach is using the instance property of the BigDecimal class. The new operator is used to create instances of the BigDecimal numbers. The add() method invokes an instance and takes another instance as a parameter. The second add() method is invoked by the result returned by the first add() method. Finally, the getValue() method is used to get the string value of the BigDecimal number. As observed the addition result for all three arrangements of numbers is the same.
a+b+c = 21.54 b+c+a = 21.54 b+a+c = 21.54