I'm working on a typescript/javascript numeric project, I obvserved some cases of accuracy issue, as compared to c++ calculation result. I searched in google and v8-dev group, bascially everyone is saying javascript number has the same accuracy as c++ double type.
I'm thinking maybe some of the accuracy issue is due to algorithm, below is an example of polynomial calculation:
typescript
code, nothing fancy, just basic complex number operations( add / sub / multiplication / division )
class Complex {
constructor(r: number = 0.0, i: number = 0.0) {
this._real = r;
this._imag = i;
}
_real: number;
_imag: number;
}
namespace Complex {
export function add(c1: Complex, c2: Complex): Complex {
return new Complex(c1._real + c2._real, c1._imag + c2._imag);
}
export function sub(c1: Complex, c2: Complex): Complex {
return new Complex(c1._real - c2._real, c1._imag - c2._imag);
}
export function mul(c1: Complex, c2: Complex): Complex {
return new Complex(
c1._real * c2._real - c1._imag * c2._imag,
c1._real * c2._imag + c1._imag * c2._real);
}
export function div(c1: Complex, c2: Complex): Complex {
return new Complex(
(c1._real * c2._real + c1._imag * c2._imag) /
(c2._real * c2._real + c2._imag * c2._imag),
(c1._imag * c2._real - c1._real * c2._imag) /
(c2._real * c2._real + c2._imag * c2._imag));
}
}
const g: Complex = new Complex(4.0, -6.000000000000001e-006);
const D: Complex = new Complex(4.0000000000086198, -6.39999999998621e-006);
const G: Complex = Complex.div(Complex.sub(g, D), Complex.add(g, D));
js result for G:
Complex {_real: -1.1548604230893913e-12, _imag: 4.9999999996432116e-8}
c++ code doing the same calculation, build with mingw-64:
#include<limits>
#include<iostream>
#include<complex>
typedef std::numeric_limits< double > dbl;
int main(int argc, char** argv) {
std::cout.precision(dbl::max_digits10);
std::complex<double> g = std::complex<double>(4.0, -6.000000000000001e-006);
std::complex<double> D = std::complex<double>(4.0000000000086198, -6.39999999998621e-006);
const std::complex<double> G = (g-D)/(g+D);
std::cout << G;
return 0;
}
c++ result for G: (-1.1549714453918537e-012,4.9999999996432057e-008)
I know the difference is not big, but I have other statistic calculatoin which is more complicated than this and didn't lose accuracy, and this part is in the middle of the calculation, if there's accuracy dip here, the final result will be even less accurate.
Does this mean c++ code is optimized? How to improve js code to have the same accuracy here? thank you!