josdejong / mathjs

An extensive math library for JavaScript and Node.js
https://mathjs.org
Apache License 2.0
14.44k stars 1.24k forks source link

datatype to matrices factories #919

Closed manofearth closed 2 years ago

manofearth commented 7 years ago

I need to preserve datatype in my calculations with matrices. Why can't I pass datatype to math.eye or math.zeroes ?

Now I'm forced to use such a workaround

const e = math.type.SparseMatrix.diagonal([5,5], math.fraction(1), 0, 'Fraction');
e._datatype = 'Fraction';

It would be less verbose to do something like:

const e = math.eye(5, 'sparse', 'Fraction');
josdejong commented 7 years ago

Most functions and operators have data as input and give data as output, and what they mostly do is make the output the same type as the input. I see though that the functions math.eye and math.zeros lack support for fractions, which may be the reason you need such an ugly workaround:

math.eye(3)                    // 3x3 matrix with numbers
math.eye(math.bignumber(3))    // 3x3 matrix with BigNumbers
math.eye(math.fraction(3))     // oops... should give a 3x3 matrix with Fractions

So I think what we should do is extend the functions eye, ones, zeros, diagonal, var, and range with support for Fractions. Would that indeed solve your issue?

manofearth commented 7 years ago

Yes, I think so. And also toArray method of Sparse matrices needs support for Fractions (where it generates zeroes).

Example scenario:

var m = math.matrix([
  [math.fraction(1), math.fraction(0)], 
  [math.fraction(3), math.fraction(4)]
], 'sparse', 'Fraction');
var e = math.eye(math.fraction(3));
var st = math.subtract(m, e); // must be a sparse matrix
var stArr = st.toArray();

for (var i=0; i < stArr.length; i++) {
  for (var j=0; j < stArr[i].length; j++) {
    console.log(stArr[i][j].toFraction()); // now I have to use a conditional expression here to determine the type of stArr[i][j] (for zeroes)
  }
}

Also it should work the same with lusolve

If type of matrix values in chain of calculations is invariable I don't need a conditional logic to process the result.

josdejong commented 7 years ago

Indeed, thanks. We'll have to go to the whole code base and check all functions that contain special behavior for BigNumbers: handle Fractions there too.

josdejong commented 2 years ago

Closing this discussion now because it has been inactive for a long time. Feel free to reopen if needed.