如何使用 LaTeX 输入格式计算矩阵行列式,例如:
1 & -2 & 2 & -1 \\
-2 & 0 & 0 & 4 \\
-1 & 2 & -1 & 3 \\
0 & 1 & 3 & 1
是否应该使用 JSON.parse(...)
将这种格式转换为数组,然后使用 JavaScript 函数计算其行列式?
注:本题原自Fastest way to compute a determinant from a LaTeX matrix input但是不可能在那里发布带有代码片段的答案,因此这里的答案本身可能很有趣。
最佳答案
这是一个在线 JavaScript 解决方案,使用 the math.js library .
在下面运行它,并将其粘贴到其中,它将起作用!
1 & -2 & 2 & -1 \\
-2 & 0 & 0 & 4 \\
-1 & 2 & -1 & 3 \\
0 & 1 & 3 & 1
$('#a').on('input', function() {
try {
var s = $('#a').val();
var t = '[[' + s.replace(/&/g, ',').replace(/\\\\/g, '],[') + ']]';
var A = JSON.parse(t);
$('#b').text(t);
$('#c').text(math.det(A));
$('#d').text(math.inv(A));
$('#e').text(math.multiply(math.det(A),math.inv(A)));
} catch (err) {
$('#b').text("Incorrect input");
$('#c').text("");
$('#d').text("");
$('#e').text("");
}
});
#a { width: 100% }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.20.2/math.min.js"></script>
<input id="a" placeholder="Paste LaTeX matrix"></input>
<br><br>Array format: <div id="b"></div>
Determinant: <div id="c"></div>
Inverse: <div id="d"></div>
Det * Inverse: <div id="e"></div>
关于javascript - 如何使用 JavaScript 计算行列式,并将输入作为 LaTeX 输入格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48797281/