Floating Point Errors with Small Integers in Complex Numbers
Wu-Li opened this issue · comments
Describe the bug
I am getting floating point rounding errors even when using small valued integers in complex numbers.
To Reproduce
Use MathJS to evaluate the expression "(2i +2)^2"
This results in the value "7.999999999999998i"
Why would a simple expression using only small integer values result in floating point inaccuracies?
The complex number uses a regular JavaScript number
for the real and imaginary part. This is a regular floating point number, which can have round-off errors due to both limited precision, and because not all decimal numbers can be represented exactly in binary zero's and one's.
See docs:
I'm not sure I understand why the number 2 can't be represented correctly in binary, isn't it just, like, 10? I can understand why some decimals might easily result in rounding errors, but there are no decimals here. How, in using this library, could you possibly anticipate the situations where rounding errors are going to occur if a handful of arithmetic operations with the number 2 are already inaccurate?
You can have a look at the implementation of pow
in Complex.js:
https://github.com/infusion/Complex.js/blob/master/complex.js#L462-L526
The implementation uses exp
, sin
, cos
, logHypot
, atan2
, and some multiplications to calculate the result, I guess that is where the round-off errors come from. It's all calculated numerically, not algebraically.