UNPKG

mathjs

Version:

Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser and offers an integrated solution to work with numbers, big numbers, complex numbers, units, and matrices.

104 lines (85 loc) 2.15 kB
<!DOCTYPE html> <html> <head> <title>math.js | pretty printing with MathJax</title> <script src="../../dist/math.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/mathjax/2.3/MathJax.js?config=TeX-AMS-MML_HTMLorMML.js"></script> <style> body, html, table td, table th, input[type=text] { font-size: 11pt; font-family: verdana, arial, sans-serif; } h1 { font-size: 11pt; } input[type=text] { padding: 5px; width: 400px; } table { border-collapse: collapse; } table td, table th { padding: 5px; border: 1px solid lightgray; } table th { background-color: lightgray; } </style> </head> <body> <h1> Expression evaluation with math.js, pretty printing with MathJax </h1> <table> <tr> <th>Expression</th> <td><input type="text" id="expr"/></td> </tr> <tr> <th>Pretty print</th> <td><div id="pretty">$$$$</div></td> </tr> <tr> <th>Result</th> <td><div id="result"></div></td> </tr> </table> <script> var expr = document.getElementById('expr'), pretty = document.getElementById('pretty'), result = document.getElementById('result'); // initialize with an example expression expr.value = 'sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2'; pretty.innerHTML = '$$' + math.parse(expr.value).toTex() + '$$'; result.innerHTML = math.eval(expr.value); expr.oninput = function () { var node = null; try { // parse the expression node = math.parse(expr.value); // evaluate the result of the expression result.innerHTML = node.compile(math).eval(); } catch (err) { result.innerHTML = '<span style="color: red;">' + err.toString() + '</span>'; } try { // export the expression to LaTeX var latex = node ? node.toTex() : ''; console.log('LaTeX expression:', latex); // display and re-render the expression var elem = MathJax.Hub.getAllJax('pretty')[0]; MathJax.Hub.Queue(['Text', elem, latex]); } catch (err) {} }; </script> </body> </html>