Compute Approximate Value of Matrix Operations With Math.js

242 Views Asked by At

I'm performing matrix calculations (e.g. computing determinants, eigenvalues, inverse matrices) in JavaScript using Math.js. I would like the computations to be performed more rapidly (it's computing them on 2X2 matrices, but it should be performing many every second, and it now causes noticeable delay), but precision isn't of that great importance (I think a couple decimal places of precision would be more than enough). Is there a way of specifying how precise the computation should be? Thanks!

Here is an example computation:

var A = [[3.5, 9], [9, 1]]
for (let x=0;x<10**5;x++){
  math.eigs(A)
  math.inv(A)
  math.det(A)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/8.1.0/math.js" integrity="sha512-ne87j5uORxbrU7+bsqeJJWfWj5in65R9PCjaQL161xtH5cesZgULVbeVAkzAAN7hnYOcrHeBas9Wbd/Lm8gXFA==" crossorigin="anonymous"></script>

In reality, I'm having these computations done every time a slider position is changed (and of course with a different matrix each time).

2

There are 2 best solutions below

1
Will On

Looking at the documentation: Yes

https://mathjs.org/docs/core/configuration.html

precision. The maximum number of significant digits for BigNumbers. This setting only applies to BigNumbers, not to numbers. Default value is 64.

I have no idea if this will actually speed up your calculations or solve your problem, but there are a number of configuration options that might help.

0
jrbe228 On

Try the ml-matrix library instead of math.js. Besides having an efficient decomposition algorithm, it also generalizes better. Math.js is limited to solving only symmetric real matrices. Here is an example of solving a more difficult binary sparse matrix with ml-matrix:

matrix = 
[
  [ 0, 1, 0, 1, 0, 1 ],
  [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 1, 0, 1, 0, 1 ],
  [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ],
  [ 1, 0, 1, 0, 0, 0 ]
]

const mlMatrix = require('ml-matrix');
const M = new mlMatrix.Matrix(matrix);
const e = new mlMatrix.EigenvalueDecomposition(M);

e.realEigenvalues -> [-1.4142135623730945, 2.220446049250313e-16, 1.4142135623730954, 0, 0, 0 ]
e.imaginaryEigenvalues -> [ 0, 0, 0, 0, 0, 0 ]