Intial Commit

This commit is contained in:
valki
2020-10-17 18:42:50 +02:00
commit 664c6d8ca3
5892 changed files with 759183 additions and 0 deletions

View File

@@ -0,0 +1,44 @@
// Note: This file is used by the file ./index.js
// factory function which defines a new data type MyType
function factory(type, config, load, typed) {
// create a new data type
function MyType (value) {
this.value = value;
}
MyType.prototype.isMyType = true;
MyType.prototype.toString = function () {
return 'MyType:' + this.value;
};
// define a new data type
typed.addType({
name: 'MyType',
test: function (x) {
// test whether x is of type MyType
return x && x.isMyType;
}
});
// define conversions if applicable
typed.addConversion({
from: 'number',
to: 'MyType',
convert: function (x) {
// convert a number to MyType
return new MyType(x);
}
});
// return the construction function, this will
// be added to math.type.MyType when imported
return MyType;
}
exports.name = 'MyType';
exports.path = 'type'; // will be imported into math.type.MyType
exports.factory = factory;
exports.lazy = false; // disable lazy loading as this factory has side
// effects: it adds a type and a conversion.

View File

@@ -0,0 +1,16 @@
var math = require('../../../index');
// import the new type MyType and the function `add` in math.js
math.import(require('./MyType'));
math.import(require('./myAdd'));
// create a shortcut to the new type.
var MyType = math.type.MyType;
// use the new type
var ans1 = math.add(new MyType(2), new MyType(3)); // returns MyType(5)
console.log(ans1.toString()); // outputs 'MyType:5'
// numbers will be converted to MyType
var ans2 = math.add(new MyType(4), 7); // returns MyType(11)
console.log(ans2.toString()); // outputs 'MyType:11'

View File

@@ -0,0 +1,16 @@
// Note: This file is used by the file ./index.js
function factory (type, config, load, typed) {
// create a new typed function using MyType
// when imported in math.js, this will extend the
// existing function `add` with support for MyType
return typed('add', {
'MyType, MyType': function (a, b) {
return new type.MyType(a.value + b.value);
}
});
}
exports.name = 'add';
exports.factory = factory;

View File

@@ -0,0 +1,51 @@
// Convert from Fraction to BigNumber
//
// In the configuration of math.js one can specify the default number type to
// be `number`, `BigNumber`, or `Fraction`. Not all functions support `Fraction`
// or `BigNumber`, and if not supported these input types will be converted to
// numbers.
//
// When `Fraction` is configured, one may want to fallback to `BigNumber`
// instead of `number`. Also, one may want to be able to mix `Fraction` and
// `BigNumber` in operations like summing them up. This can be achieved by
// adding an extra conversion to the list of conversions as demonstrated in
// this example.
// Load the math.js core (contains only `import` and `config`)
var core = require('../../core');
var math = core.create();
// Configure to use fractions by default
math.config({number: 'Fraction'});
// Add a conversion from Faction -> BigNumber
// this conversion:
// - must be inserted in the conversions list before the conversion Fraction -> number
// - must be added to the conversions before loading functions into math.js
math.typed.conversions.unshift({
from: 'Fraction',
to: 'BigNumber',
convert: function (fraction) {
return new math.type.BigNumber(fraction.n).div(fraction.d);
}
});
// Import all data types, functions, constants, the expression parser, etc.
math.import(require('../../lib'));
// Operators `add` and `divide` do have support for Fractions, so the result
// will simply be a Fraction (default behavior of math.js).
var ans1 = math.eval('1/3 + 1/4');
console.log(math.typeof(ans1), math.format(ans1));
// outputs "Fraction 7/12"
// Function sqrt doesn't have Fraction support, will now fall back to BigNumber
// instead of number.
var ans2 = math.eval('sqrt(4)');
console.log(math.typeof(ans2), math.format(ans2));
// outputs "BigNumber 2"
// We can now do operations with mixed Fractions and BigNumbers
var ans3 = math.add(math.fraction(2, 5), math.bignumber(3));
console.log(math.typeof(ans3), math.format(ans3));
// outputs "BigNumber 3.4"

View File

@@ -0,0 +1,99 @@
/**
* The expression parser of math.js has support for letting functions
* parse and evaluate arguments themselves, instead of calling them with
* evaluated arguments.
*
* By adding a property `raw` with value true to a function, the function
* will be invoked with unevaluated arguments, allowing the function
* to process the arguments in a customized way.
*/
var math = require('../../index');
/**
* Calculate the numeric integration of a function
* @param {Function} f
* @param {number} start
* @param {number} end
* @param {number} [step=0.01]
*/
function integrate(f, start, end, step) {
var total = 0;
step = step || 0.01;
for (var x = start; x < end; x += step) {
total += f(x + step / 2) * step;
}
return total;
}
/**
* A transformation for the integrate function. This transformation will be
* invoked when the function is used via the expression parser of math.js.
*
* Syntax:
*
* integrate(integrand, variable, start, end)
* integrate(integrand, variable, start, end, step)
*
* Usage:
*
* math.eval('integrate(2*x, x, 0, 2)')
* math.eval('integrate(2*x, x, 0, 2, 0.01)')
*
* @param {Array.<math.expression.node.Node>} args
* Expects the following arguments: [f, x, start, end, step]
* @param {Object} math
* @param {Object} [scope]
*/
integrate.transform = function (args, math, scope) {
// determine the variable name
if (args[1] instanceof math.expression.node.SymbolNode) {
var variable = args[1].name;
}
else {
throw new Error('Second argument must be a symbol');
}
// evaluate start, end, and step
var start = args[2].compile().eval(scope);
var end = args[3].compile().eval(scope);
var step = args[4] && args[4].compile().eval(scope); // step is optional
// create a new scope, linked to the provided scope. We use this new scope
// to apply the variable.
var fnScope = Object.create(scope);
// construct a function which evaluates the first parameter f after applying
// a value for parameter x.
var fnCode = args[0].compile();
var f = function (x) {
fnScope[variable] = x;
return fnCode.eval(fnScope);
};
// execute the integration
return integrate(f, start, end, step);
};
// mark the transform function with a "rawArgs" property, so it will be called
// with uncompiled, unevaluated arguments.
integrate.transform.rawArgs = true;
// import the function into math.js. Raw functions must be imported in the
// math namespace, they can't be used via `eval(scope)`.
math.import({
integrate: integrate
});
// use the function in JavaScript
function f(x) {
return math.pow(x, 0.5);
}
console.log(math.integrate(f, 0, 1)); // outputs 0.6667254718034714
// use the function via the expression parser
console.log(math.eval('integrate(x^0.5, x, 0, 1)')); // outputs 0.6667254718034714
// use the function via the expression parser (2)
var scope = {};
math.eval('f(x) = 2 * x', scope);
console.log(math.eval('integrate(f(x), x, 0, 2)', scope)); // outputs 4.000000000000003

View File

@@ -0,0 +1,44 @@
// Load the math.js core
var core = require('../../core');
// Create a new, empty math.js instance
// It will only contain methods `import` and `config`
var math = core.create();
// load the data types you need. Let's say you just want to use fractions,
// but no matrices, complex numbers, bignumbers, and other stuff.
//
// To load all data types:
//
// math.import(require('../../lib/type'));
//
math.import(require('../../lib/type/fraction'));
// Load the functions you need.
//
// To load all functions:
//
// math.import(require('../../lib/function'));
//
// To load all functions of a specific category:
//
// math.import(require('../../lib/function/arithmetic'));
//
math.import(require('../../lib/function/arithmetic/add'));
math.import(require('../../lib/function/arithmetic/subtract'));
math.import(require('../../lib/function/arithmetic/multiply'));
math.import(require('../../lib/function/arithmetic/divide'));
math.import(require('../../lib/function/string/format'));
// Use the loaded functions
var a = math.fraction(1, 3);
var b = math.fraction(3, 7);
var c = math.add(a, b);
console.log('result:', math.format(c)); // outputs "result: 16/21"
// Now, when bundling your application for use in the browser, only the used
// parts of math.js will be bundled. For example to create a bundle using
// browserify:
//
// browserify custom_loading.js -o custom_loading.bundle.js
//

View File

@@ -0,0 +1,53 @@
var math = require('../../index');
// Filter an expression tree
console.log('Filter all symbol nodes "x" in the expression "x^2 + x/4 + 3*y"');
var node = math.parse('x^2 + x/4 + 3*y');
var filtered = node.filter(function (node) {
return node.isSymbolNode && node.name == 'x';
});
// returns an array with two entries: two SymbolNodes 'x'
filtered.forEach(function (node) {
console.log(node.type, node.toString())
});
// outputs:
// SymbolNode x
// SymbolNode x
// Traverse an expression tree
console.log();
console.log('Traverse the expression tree of expression "3 * x + 2"');
var node1 = math.parse('3 * x + 2');
node1.traverse(function (node, path, parent) {
switch (node.type) {
case 'OperatorNode': console.log(node.type, node.op); break;
case 'ConstantNode': console.log(node.type, node.value); break;
case 'SymbolNode': console.log(node.type, node.name); break;
default: console.log(node.type);
}
});
// outputs:
// OperatorNode +
// OperatorNode *
// ConstantNode 3
// SymbolNode x
// ConstantNode 2
// transform an expression tree
console.log();
console.log('Replace all symbol nodes "x" in expression "x^2 + 5*x" with a constant 3');
var node2 = math.parse('x^2 + 5*x');
var transformed = node2.transform(function (node, path, parent) {
if (node.isSymbolNode && node.name == 'x') {
return new math.expression.node.ConstantNode(3);
}
else {
return node;
}
});
console.log(transformed.toString());
// outputs: '(3 ^ 2) + (5 * 3)'

View File

@@ -0,0 +1,49 @@
/**
* Function transforms
*
* When using functions via the expression parser, it is possible to preprocess
* function arguments and post process a functions return value by writing a
* *transform* for the function. A transform is a function wrapping around a
* function to be transformed or completely replaces a function.
*/
var math = require('../../index');
// create a function
function addIt(a, b) {
return a + b;
}
// attach a transform function to the function addIt
addIt.transform = function (a, b) {
console.log('input: a=' + a + ', b=' + b);
// we can manipulate the input arguments here before executing addIt
var res = addIt(a, b);
console.log('result: ' + res);
// we can manipulate the result here before returning
return res;
};
// import the function into math.js
math.import({
addIt: addIt
});
// use the function via the expression parser
console.log('Using expression parser:');
console.log('2+4=' + math.eval('addIt(2, 4)'));
// This will output:
//
// input: a=2, b=4
// result: 6
// 2+4=6
// when used via plain JavaScript, the transform is not invoked
console.log('');
console.log('Using plain JavaScript:');
console.log('2+4=' + math.addIt(2, 4));
// This will output:
//
// 6

View File

@@ -0,0 +1,23 @@
var math = require('mathjs');
var workerpool = require('workerpool');
// disable the import function so the math.js instance cannot be changed
function noImport() {
throw new Error('function import is disabled.');
}
math.import({'import': noImport}, {override: true});
/**
* Evaluate an expression
* @param {string} expr
* @return {string} result
*/
function evaluate (expr) {
var ans = math.eval(expr);
return math.format(ans);
}
// create a worker and register public functions
workerpool.worker({
evaluate: evaluate
});

View File

@@ -0,0 +1,79 @@
/**
* This example demonstrates how to run math.js in a child process with limited
* execution time.
*
* Prerequisites:
*
* npm install express workerpool
*
* Start the server:
*
* node ./server.js
*
* Make a request to the server:
*
* GET http://localhost:8080/mathjs?expr=sqrt(16)
*
* Note that the query parameter `expr` should be properly url encoded.
*/
try {
var express = require('express');
var workerpool = require('workerpool');
}
catch (err) {
console.log('Error: To run this example, install express and workerpool first via:\n\n' +
' npm install express workerpool\n');
process.exit();
}
var app = express();
var pool = workerpool.pool(__dirname + '/math_worker.js');
var TIMEOUT = 10000; // milliseconds
/**
* GET /mathjs?expr=...
*/
app.get('/mathjs', function (req, res) {
var expr = req.query.expr;
if (expr === undefined) {
return res.status(400).send('Error: Required query parameter "expr" missing in url.');
}
pool.exec('evaluate', [expr])
.timeout(TIMEOUT)
.then(function (result) {
res.send(result);
})
.catch(function (err) {
res.status(400).send(formatError(err));
});
});
/**
* Format error messages as string
* @param {Error} err
* @return {String} message
*/
function formatError (err) {
if (err instanceof workerpool.Promise.TimeoutError) {
return 'TimeoutError: Evaluation exceeded maximum duration of ' + TIMEOUT / 1000 + ' seconds';
}
else {
return err.toString();
}
}
// handle uncaught exceptions so the application cannot crash
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
console.trace();
});
// start the server
var PORT = process.env.PORT || 8080;
app.listen(PORT, function() {
console.log('Listening at http://localhost:' + PORT);
console.log('Example request:\n GET http://localhost:' + PORT + '/mathjs?expr=sqrt(16)');
});

View File

@@ -0,0 +1,33 @@
// algebra
//
// math.js has support for symbolic computation (CAS). It can parse
// expressions in an expression tree and do algebraic operations like
// simplification and derivation on this tree.
// load math.js (using node.js)
var math = require('../index');
// simplify an expression
console.log('simplify expressions');
console.log(math.simplify('3 + 2 / 4').toString()); // '7 / 2'
console.log(math.simplify('2x + 3x').toString()); // '5 * x'
console.log(math.simplify('x^2 + x + 3 + x^2').toString()); // '2 * x ^ 2 + x + 3'
console.log(math.simplify('x * y * -x / (x ^ 2)').toString()); // '-y'
// work with an expression tree, evaluate results
var f = math.parse('2x + x');
var simplified = math.simplify(f);
console.log(simplified.toString()); // '3 * x'
console.log(simplified.eval({x: 4})); // 12
console.log()
// calculate a derivative
console.log('calculate derivatives');
console.log(math.derivative('2x^2 + 3x + 4', 'x').toString()); // '4 * x + 3'
console.log(math.derivative('sin(2x)', 'x').toString()); // '2 * cos(2 * x)'
// work with an expression tree, evaluate results
var h = math.parse('x^2 + x');
var dh = math.derivative(h, 'x');
console.log(dh.toString()); // '2 * x + 1'
console.log(dh.eval({x: 3})); // '7'

View File

@@ -0,0 +1,50 @@
// basic usage
// load math.js (using node.js)
var math = require('../index');
// functions and constants
console.log('functions and constants');
print(math.round(math.e, 3)); // 2.718
print(math.atan2(3, -3) / math.pi); // 0.75
print(math.log(10000, 10)); // 4
print(math.sqrt(-4)); // 2i
print(math.pow([[-1, 2], [3, 1]], 2)); // [[7, 0], [0, 7]]
print(math.derivative('x^2 + x', 'x')); // 2 * x + 1
console.log();
// expressions
console.log('expressions');
print(math.eval('1.2 * (2 + 4.5)')); // 7.8
print(math.eval('5.08 cm to inch')); // 2 inch
print(math.eval('sin(45 deg) ^ 2')); // 0.5
print(math.eval('9 / 3 + 2i')); // 3 + 2i
print(math.eval('det([-1, 2; 3, 1])')); // -7
console.log();
// chained operations
console.log('chained operations');
var a = math.chain(3)
.add(4)
.multiply(2)
.done();
print(a); // 14
console.log();
// mixed use of different data types in functions
console.log('mixed use of data types');
print(math.add(4, [5, 6])); // number + Array, [9, 10]
print(math.multiply(math.unit('5 mm'), 3)); // Unit * number, 15 mm
print(math.subtract([2, 3, 4], 5)); // Array - number, [-3, -2, -1]
print(math.add(math.matrix([2, 3]), [4, 5])); // Matrix + Array, [6, 8]
console.log();
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
var precision = 14;
console.log(math.format(value, precision));
}

View File

@@ -0,0 +1,42 @@
// BigNumbers
// load math.js (using node.js)
var math = require('../index');
// configure the default type of numbers as BigNumbers
math.config({
number: 'BigNumber', // Default type of number:
// 'number' (default), 'BigNumber', or 'Fraction'
precision: 20 // Number of significant digits for BigNumbers
});
console.log('round-off errors with numbers');
print(math.add(0.1, 0.2)); // number, 0.30000000000000004
print(math.divide(0.3, 0.2)); // number, 1.4999999999999998
console.log();
console.log('no round-off errors with BigNumbers');
print(math.add(math.bignumber(0.1), math.bignumber(0.2))); // BigNumber, 0.3
print(math.divide(math.bignumber(0.3), math.bignumber(0.2))); // BigNumber, 1.5
console.log();
console.log('create BigNumbers from strings when exceeding the range of a number');
print(math.bignumber(1.2e+500)); // BigNumber, Infinity WRONG
print(math.bignumber('1.2e+500')); // BigNumber, 1.2e+500
console.log();
// one can work conveniently with BigNumbers using the expression parser.
// note though that BigNumbers are only supported in arithmetic functions
console.log('use BigNumbers in the expression parser');
print(math.eval('0.1 + 0.2')); // BigNumber, 0.3
print(math.eval('0.3 / 0.2')); // BigNumber, 1.5
console.log();
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
console.log(math.format(value));
}

View File

@@ -0,0 +1,130 @@
<!DOCTYPE html>
<html>
<head>
<title>math.js | angle configuration</title>
<style>
body, input, select {
font: 11pt sans-serif;
}
input, select, th, #result {
padding: 5px 10px;
}
th {
text-align: left;
}
</style>
<script src="../../dist/math.js"></script>
</head>
<body>
<p>
This code example extends the trigonometric functions of math.js with configurable angles: degrees, radians, or gradians.
</p>
<table>
<tr>
<th>Angles</th>
<td>
<select id="angles">
<option value="deg">deg</option>
<option value="grad">grad</option>
<option value="rad">rad</option>
</select>
</td>
</tr>
<tr>
<th>Expression</th>
<td>
<input id="expression" type="text" value="sin(45)" />
<input id="evaluate" type="button" value="Evaluate">
</td>
</tr>
<tr>
<th>Result</th>
<td id="result"></td>
</tr>
</table>
<script>
var replacements = {};
// our extended configuration options
var config = {
angles: 'deg' // 'rad', 'deg', 'grad'
};
// create trigonometric functions replacing the input depending on angle config
['sin', 'cos', 'tan', 'sec', 'cot', 'csc'].forEach(function(name) {
var fn = math[name]; // the original function
var fnNumber = function (x) {
// convert from configured type of angles to radians
switch (config.angles) {
case 'deg':
return fn(x / 360 * 2 * Math.PI);
case 'grad':
return fn(x / 400 * 2 * Math.PI);
default:
return fn(x);
}
};
// create a typed-function which check the input types
replacements[name] = math.typed(name, {
'number': fnNumber,
'Array | Matrix': function (x) {
return math.map(x, fnNumber);
}
});
});
// create trigonometric functions replacing the output depending on angle config
['asin', 'acos', 'atan', 'atan2', 'acot', 'acsc', 'asec'].forEach(function(name) {
var fn = math[name]; // the original function
var fnNumber = function (x) {
var result = fn(x);
if (typeof result === 'number') {
// convert to radians to configured type of angles
switch(config.angles) {
case 'deg': return result / 2 / Math.PI * 360;
case 'grad': return result / 2 / Math.PI * 400;
default: return result;
}
}
return result;
};
// create a typed-function which check the input types
replacements[name] = math.typed(name, {
'number': fnNumber,
'Array | Matrix': function (x) {
return math.map(x, fnNumber);
}
});
});
// import all replacements into math.js, override existing trigonometric functions
math.import(replacements, {override: true});
// pointers to the input elements
var expression = document.getElementById('expression');
var evaluate = document.getElementById('evaluate');
var result = document.getElementById('result');
var angles = document.getElementById('angles');
// attach event handlers for select box and button
angles.onchange = function () {
config.angles = this.value;
};
evaluate.onclick = function () {
result.innerHTML = math.eval(expression.value);
};
</script>
</body>
</html>

View File

@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
<head>
<title>math.js | basic usage</title>
<script src="../../dist/math.js"></script>
</head>
<body>
<script>
function print(value) {
var precision = 14;
document.write(math.format(value, precision) + '<br>');
}
// functions and constants
print(math.round(math.e, 3)); // 2.718
print(math.atan2(3, -3) / math.pi); // 0.75
print(math.log(1000, 10)); // 3
print(math.sqrt(-4)); // 2i
print(math.pow([[-1, 2], [3, 1]], 2)); // [[7, 0], [0, 7]]
print(math.derivative('x^2 + x', 'x')); // 2 * x + 1
// expressions
print(math.eval('12 / (2.3 + 0.7)')); // 4
print(math.eval('5.08 cm to inch')); // 2 inch
print(math.eval('9 / 3 + 2i')); // 3 + 2i
print(math.eval('det([-1, 2; 3, 1])')); // -7
// chained operations
var a = math.chain(3)
.add(4)
.multiply(2)
.done();
print(a); // 14
</script>
</body>
</html>

View File

@@ -0,0 +1,90 @@
<!DOCTYPE html>
<html>
<head>
<title>math.js | currency conversion</title>
<script src="../../dist/math.js"></script>
<style>
body,
html,
input {
font-size: 11pt;
font-family: verdana, arial, sans-serif;
color: #4d4d4d;
max-width: 600px;
}
h1 {
font-size: 120%;
}
input {
padding: 5px;
width: 400px;
}
</style>
</head>
<body>
<h1>Currency conversion with math.js</h1>
<p>
This example demonstrates how you can fetch actual currencies from <a href="http://fixer.io">fixer.io</a> and use them in math.js.
</p>
<p id="info">
fetching currencies...
</p>
<p>
<label for="expr">Enter an expression with currencies:</label>
</p>
<div id="form" style="display: none;">
<p>
<input id="expr" value="5 EUR + 2 * 3 EUR in USD" /><br/>
</p>
<p id="result"></p>
</div>
<script>
fetchAndImportCurrencies()
.then(function (currencies) {
document.getElementById('expr').oninput = evaluate;
document.getElementById('form').style.display = '';
document.getElementById('info').innerHTML = 'Available currencies: ' + currencies.join(', ');
evaluate();
})
function fetchAndImportCurrencies () {
// fetch actual currency conversion rates
return fetch('https://api.fixer.io/latest')
.then(function (response) {
return response.json();
}).then(function (data) {
// import the currencies
math.createUnit(data.base)
Object.keys(data.rates).forEach(function (currency) {
math.createUnit(currency, math.unit(1 / data.rates[currency], data.base));
});
// return an array with all available currencies
return Object.keys(data.rates).concat(data.base);
});
}
function evaluate () {
var expr = document.getElementById('expr');
var result = document.getElementById('result');
try {
var resultStr = math.format(math.eval(expr.value), {notation: 'fixed', precision: 2})
result.innerHTML = '<span style="color: dodgerblue;">' + resultStr + '</span>';
}
catch (err) {
result.innerHTML = '<span style="color: red;">' + err.toString() + '</span>';
}
}
</script>
</body>
</html>

View File

@@ -0,0 +1,80 @@
<!DOCTYPE html>
<html>
<head>
<title>math.js | custom separators</title>
<style>
body, input, select {
font: 11pt sans-serif;
}
input, select, th, #result {
padding: 5px 10px;
}
th {
text-align: left;
}
</style>
<script src="../../dist/math.js"></script>
</head>
<body>
<p>
This code example shows how to apply custom separators for function arguments and decimal separator.
</p>
<table>
<tr>
<th>Argument separator</th>
<td>
<input id="args" type="text" value=";">
</td>
</tr>
<tr>
<th>Decimal separator</th>
<td>
<input id="decimals" type="text" value=",">
</td>
</tr>
<tr>
<th>Expression</th>
<td>
<input id="expression" type="text" value="sum(3,4; 2,1; 2,0)" />
<input id="evaluate" type="button" value="Evaluate">
</td>
</tr>
<tr>
<th>Result</th>
<td id="result"></td>
</tr>
</table>
<script>
// pointers to the input elements
var expression = document.getElementById('expression');
var evaluate = document.getElementById('evaluate');
var result = document.getElementById('result');
var args = document.getElementById('args');
var decimals = document.getElementById('decimals');
// attach event handler to the button
evaluate.onclick = function () {
// replace the custom separators in the input with the default separators
var expr = expression.value
.replace(new RegExp('\\' + decimals.value + '|\\' + args.value, 'g'), function (match) {
return match == decimals.value ? '.': ',';
});
// do the actual evaluation
var res = math.eval(expr);
// replace the default separators in the output with custom separators
result.innerHTML = res.toString()
.replace(new RegExp(',|\\.', 'g'), function (match) {
return match == '.' ? decimals.value : args.value;
});
};
</script>
</body>
</html>

View File

@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html>
<head>
<title>math.js | old browsers</title>
<!-- es5-shim for old browsers (IE8 and older) -->
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/2.2.0/es5-shim.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/2.2.0/es5-sham.min.js"></script>
<script src="../../dist/math.js"></script>
</head>
<body>
<p>
To run math.js in old browsers (IE8 and older),
the <a href="https://github.com/kriskowal/es5-shim">es5-shim</a> library is needed.
</p>
<script>
function print(value) {
var precision = 14;
document.write(math.format(value, precision) + '<br>');
}
// functions and constants
print(math.round(math.e, 3)); // 2.718
print(math.atan2(3, -3) / math.pi); // 0.75
print(math.log(1000, 10)); // 3
print(math.sqrt(-4)); // 2i
print(math.pow([[-1, 2], [3, 1]], 2)); // [[7, 0], [0, 7]]
// expressions
print(math.eval('12 / (2.3 + 0.7)')); // 4
print(math.eval('5.08 cm to inch')); // 2 inch
print(math.eval('9 / 3 + 2i')); // 3 + 2i
print(math.eval('det([-1, 2; 3, 1])')); // -7
// chained operations
var a = math.chain(3)
.add(4)
.multiply(2)
.done();
print(a); // 14
</script>
</body>
</html>

View File

@@ -0,0 +1,69 @@
<!DOCTYPE html>
<html>
<head>
<title>math.js | plot</title>
<script src="../../dist/math.js"></script>
<!-- load http://maurizzzio.github.io/function-plot/ -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://wzrd.in/standalone/function-plot@1.14.0"></script>
<style>
input[type=text] {
width: 300px;
}
input {
padding: 6px;
}
body, html, input {
font-family: sans-serif;
font-size: 11pt;
}
form {
margin: 20px 0;
}
</style>
</head>
<body>
<form id="form">
<label for="eq">Enter an equation:</label>
<input type="text" id="eq" value="4 * sin(x) + 5 * cos(x/2)" />
<input type="submit" value="Draw" />
</form>
<div id="plot"></div>
<p>
Plot library: <a href="https://github.com/maurizzzio/function-plot">https://github.com/maurizzzio/function-plot</a>
</p>
<script>
function draw() {
try {
functionPlot({
target: '#plot',
data: [{
fn: document.getElementById('eq').value,
sampler: 'builtIn', // this will make function-plot use the evaluator of math.js
graphType: 'polyline'
}]
});
}
catch (err) {
console.log(err);
alert(err);
}
}
document.getElementById('form').onsubmit = function (event) {
event.preventDefault();
draw();
};
draw();
</script>
</body>
</html>

View File

@@ -0,0 +1,114 @@
<!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>
<b>Parenthesis option:</b>
<input type="radio" name="parenthesis" value="keep" onclick="parenthesis = 'keep'; expr.oninput();" checked>keep
<input type="radio" name="parenthesis" value="auto" onclick="parenthesis = 'auto'; expr.oninput();">auto
<input type="radio" name="parenthesis" value="all" onclick="parenthesis = 'all'; expr.oninput();">all
<br/>
<b>Implicit multiplication:</b>
<input type="radio" name="implicit" value="hide" onclick="implicit = 'hide'; expr.oninput();" checked>hide
<input type="radio" name="implicit" value="show" onclick="implicit = 'show'; expr.oninput();">show
<script>
var expr = document.getElementById('expr'),
pretty = document.getElementById('pretty'),
result = document.getElementById('result'),
parenthesis = 'keep',
implicit = 'hide';
// 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({parenthesis: parenthesis}) + '$$';
result.innerHTML = math.format(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 = math.format(node.compile().eval());
}
catch (err) {
result.innerHTML = '<span style="color: red;">' + err.toString() + '</span>';
}
try {
// export the expression to LaTeX
var latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : '';
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>

View File

@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title>math.js | require.js loading</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.min.js"></script>
</head>
<body>
<script>
// load math.js using require.js
require(['../../dist/math.js'], function (math) {
// evaluate some expression
var result = math.eval('1.2 * (2 + 4.5)');
document.write(result);
});
</script>
</body>
</html>

View File

@@ -0,0 +1,79 @@
<!DOCTYPE html>
<html>
<head>
<title>math.js | web workers</title>
</head>
<body>
<p>
In this example, a math.js parser is running in a separate
<a href="http://www.html5rocks.com/en/tutorials/workers/basics/">web worker</a>,
preventing the user interface from freezing during heavy calculations.
</p>
<p id="results"></p>
<script>
/**
* MathWorker evaluates expressions asynchronously in a web worker.
*
* Example usage:
*
* var worker = new MathWorker();
* var expr = '12 / (2.3 + 0.7)';
* worker.eval(expr, function (err, result) {
* console.log(err, result)
* });
*/
function MathWorker () {
this.worker = new Worker('worker.js');
this.callbacks = {};
this.seq = 0;
// create a listener to receive responses from the web worker
var me = this;
this.worker.addEventListener('message', function(event) {
var response = JSON.parse(event.data);
// find the callback corresponding to this response
var callback = me.callbacks[response.id];
delete me.callbacks[response.id];
// call the requests callback with the result
callback(response.err, response.result);
}, false);
}
/**
* Evaluate an expression
* @param {string} expr
* @param {Function} callback Called as callback(err, result)
*/
MathWorker.prototype.eval = function eval (expr, callback) {
// build a request,
// add an id so we can link returned responses to the right callback
var id = this.seq++;
var request = {
id: id,
expr: expr
};
// queue the callback, it will be called when the worker returns the result
this.callbacks[id] = callback;
// send the request to the worker
this.worker.postMessage(JSON.stringify(request));
};
// create a MathWorker
var worker = new MathWorker();
// evaluate an expression via the worker
worker.eval('12 / (2.3 + 0.7)', function (err, result) {
document.getElementById('results').innerHTML += 'result: ' + result + '<br>';
});
</script>
</body>
</html>

View File

@@ -0,0 +1,30 @@
importScripts('../../../dist/math.js');
// create a parser
var parser = math.parser();
self.addEventListener('message', function(event) {
var request = JSON.parse(event.data),
result = null,
err = null;
try {
// evaluate the expression
result = parser.eval(request.expr);
}
catch (e) {
// return the error
err = e;
}
// build a response
var response = {
id: request.id,
result: result,
err: err
};
// send the response back
self.postMessage(JSON.stringify(response));
}, false);

View File

@@ -0,0 +1,58 @@
// chaining
// load math.js (using node.js)
var math = require('../index');
// create a chained operation using the function `chain(value)`
// end a chain using done(). Let's calculate (3 + 4) * 2
var a = math.chain(3)
.add(4)
.multiply(2)
.done();
print(a); // 14
// Another example, calculate square(sin(pi / 4))
var b = math.chain(math.pi)
.divide(4)
.sin()
.square()
.done();
print(b); // 0.5
// A chain has a few special methods: done, toString, valueOf, get, and set.
// these are demonstrated in the following examples
// toString will return a string representation of the chain's value
var chain = math.chain(2).divide(3);
var str = chain.toString();
print(str); // "0.6666666666666666"
// a chain has a function .valueOf(), which returns the value hold by the chain.
// This allows using it in regular operations. The function valueOf() acts the
// same as function done().
print(chain.valueOf()); // 0.66666666666667
print(chain + 2); // 2.6666666666667
// the function subset can be used to get or replace sub matrices
var array = [[1, 2], [3, 4]];
var v = math.chain(array)
.subset(math.index(1, 0))
.done();
print(v); // 3
var m = math.chain(array)
.subset(math.index(0, 0), 8)
.multiply(3)
.done();
print(m); // [[24, 6], [9, 12]]
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
var precision = 14;
console.log(math.format(value, precision));
}

View File

@@ -0,0 +1,55 @@
// complex numbers
// load math.js (using node.js)
var math = require('../index');
// create a complex number with a numeric real and complex part
console.log('create and manipulate complex numbers');
var a = math.complex(2, 3);
print(a); // 2 + 3i
// read the real and complex parts of the complex number
print(a.re); // 2
print(a.im); // 3
// clone a complex value
var clone = a.clone();
print(clone); // 2 + 3i
// adjust the complex value
a.re = 5;
print(a); // 5 + 3i
// create a complex number by providing a string with real and complex parts
var b = math.complex('3-7i');
print(b); // 3 - 7i
console.log();
// perform operations with complex numbers
console.log('perform operations');
print(math.add(a, b)); // 8 - 4i
print(math.multiply(a, b)); // 36 - 26i
print(math.sin(a)); // -9.6541254768548 + 2.8416922956064i
// some operations will return a complex number depending on the arguments
print(math.sqrt(4)); // 2
print(math.sqrt(-4)); // 2i
// create a complex number from polar coordinates
console.log('create complex numbers with polar coordinates');
var c = math.complex({r: math.sqrt(2), phi: math.pi / 4});
print(c); // 1 + i
// get polar coordinates of a complex number
var d = math.complex(3, 4);
console.log(d.abs(), d.arg()); // radius = 5, phi = 0.9272952180016122
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
var precision = 14;
console.log(math.format(value, precision));
}

View File

@@ -0,0 +1,191 @@
/**
* Expressions can be evaluated in various ways:
*
* 1. using the function math.eval
* 2. using the function math.parse
* 3. using a parser. A parser contains functions eval and parse,
* and keeps a scope with assigned variables in memory
*/
// load math.js (using node.js)
var math = require('../index');
// 1. using the function math.eval
//
// Function `eval` accepts a single expression or an array with
// expressions as first argument, and has an optional second argument
// containing a scope with variables and functions. The scope is a regular
// JavaScript Object. The scope will be used to resolve symbols, and to write
// assigned variables or function.
console.log('1. USING FUNCTION MATH.EVAL');
// evaluate expressions
console.log('\nevaluate expressions');
print(math.eval('sqrt(3^2 + 4^2)')); // 5
print(math.eval('sqrt(-4)')); // 2i
print(math.eval('2 inch to cm')); // 5.08 cm
print(math.eval('cos(45 deg)')); // 0.70711
// evaluate multiple expressions at once
console.log('\nevaluate multiple expressions at once');
print(math.eval([
'f = 3',
'g = 4',
'f * g'
])); // [3, 4, 12]
// provide a scope (just a regular JavaScript Object)
console.log('\nevaluate expressions providing a scope with variables and functions');
var scope = {
a: 3,
b: 4
};
// variables can be read from the scope
print(math.eval('a * b', scope)); // 12
// variable assignments are written to the scope
print(math.eval('c = 2.3 + 4.5', scope)); // 6.8
print(scope.c); // 6.8
// scope can contain both variables and functions
scope.hello = function (name) {
return 'hello, ' + name + '!';
};
print(math.eval('hello("hero")', scope)); // "hello, hero!"
// define a function as an expression
var f = math.eval('f(x) = x ^ a', scope);
print(f(2)); // 8
print(scope.f(2)); // 8
// 2. using function math.parse
//
// Function `math.parse` parses expressions into a node tree. The syntax is
// similar to function `math.eval`.
// Function `parse` accepts a single expression or an array with
// expressions as first argument. The function returns a node tree, which
// then can be compiled against math, and then evaluated against an (optional
// scope. This scope is a regular JavaScript Object. The scope will be used
// to resolve symbols, and to write assigned variables or function.
console.log('\n2. USING FUNCTION MATH.PARSE');
// parse an expression
console.log('\nparse an expression into a node tree');
var node1 = math.parse('sqrt(3^2 + 4^2)');
print(node1.toString()); // "sqrt((3 ^ 2) + (4 ^ 2))"
// compile and evaluate the compiled code
// you could also do this in two steps: node1.compile().eval()
print(node1.eval()); // 5
// provide a scope
console.log('\nprovide a scope');
var node2 = math.parse('x^a');
var code2 = node2.compile();
print(node2.toString()); // "x ^ a"
var scope = {
x: 3,
a: 2
};
print(code2.eval(scope)); // 9
// change a value in the scope and re-evaluate the node
scope.a = 3;
print(code2.eval(scope)); // 27
// 3. using function math.compile
//
// Function `math.compile` compiles expressions into a node tree. The syntax is
// similar to function `math.eval`.
// Function `compile` accepts a single expression or an array with
// expressions as first argument, and returns an object with a function eval
// to evaluate the compiled expression. On evaluation, an optional scope can
// be provided. This scope will be used to resolve symbols, and to write
// assigned variables or function.
console.log('\n3. USING FUNCTION MATH.COMPILE');
// parse an expression
console.log('\ncompile an expression');
var code3 = math.compile('sqrt(3^2 + 4^2)');
// evaluate the compiled code
print(code3.eval()); // 5
// provide a scope for the variable assignment
console.log('\nprovide a scope');
var code2 = math.compile('a = a + 3');
var scope = {
a: 7
};
code2.eval(scope);
print(scope.a); // 10
// 4. using a parser
//
// In addition to the static functions `math.eval` and `math.parse`, math.js
// contains a parser with functions `eval` and `parse`, which automatically
// keeps a scope with assigned variables in memory. The parser also contains
// some convenience methods to get, set, and remove variables from memory.
console.log('\n4. USING A PARSER');
var parser = math.parser();
// evaluate with parser
console.log('\nevaluate expressions');
print(parser.eval('sqrt(3^2 + 4^2)')); // 5
print(parser.eval('sqrt(-4)')); // 2i
print(parser.eval('2 inch to cm')); // 5.08 cm
print(parser.eval('cos(45 deg)')); // 0.70711
// define variables and functions
console.log('\ndefine variables and functions');
print(parser.eval('x = 7 / 2')); // 3.5
print(parser.eval('x + 3')); // 6.5
print(parser.eval('f(x, y) = x^y')); // f(x, y)
print(parser.eval('f(2, 3)')); // 8
// manipulate matrices
// Note that matrix indexes in the expression parser are one-based with the
// upper-bound included. On a JavaScript level however, math.js uses zero-based
// indexes with an excluded upper-bound.
console.log('\nmanipulate matrices');
print(parser.eval('k = [1, 2; 3, 4]')); // [[1, 2], [3, 4]]
print(parser.eval('l = zeros(2, 2)')); // [[0, 0], [0, 0]]
print(parser.eval('l[1, 1:2] = [5, 6]')); // [[5, 6], [0, 0]]
print(parser.eval('l[2, :] = [7, 8]')); // [[5, 6], [7, 8]]
print(parser.eval('m = k * l')); // [[19, 22], [43, 50]]
print(parser.eval('n = m[2, 1]')); // 43
print(parser.eval('n = m[:, 1]')); // [[19], [43]]
// get and set variables and functions
console.log('\nget and set variables and function in the scope of the parser');
var x = parser.get('x');
console.log('x =', x); // x = 7
var f = parser.get('f');
console.log('f =', math.format(f)); // f = f(x, y)
var g = f(3, 3);
console.log('g =', g); // g = 27
parser.set('h', 500);
print(parser.eval('h / 2')); // 250
parser.set('hello', function (name) {
return 'hello, ' + name + '!';
});
print(parser.eval('hello("hero")')); // "hello, hero!"
// clear defined functions and variables
parser.clear();
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
var precision = 14;
console.log(math.format(value, precision));
}

View File

@@ -0,0 +1,71 @@
// Fractions
// load math.js (using node.js)
var math = require('../index');
// configure the default type of numbers as Fractions
math.config({
number: 'Fraction' // Default type of number:
// 'number' (default), 'BigNumber', or 'Fraction'
});
console.log('basic usage');
printRatio(math.fraction(0.125)); // Fraction, 1/8
printRatio(math.fraction(0.32)); // Fraction, 8/25
printRatio(math.fraction('1/3')); // Fraction, 1/3
printRatio(math.fraction('0.(3)')); // Fraction, 1/3
printRatio(math.fraction(2, 3)); // Fraction, 2/3
printRatio(math.fraction('0.(285714)')); // Fraction, 2/7
console.log();
console.log('round-off errors with numbers');
print(math.add(0.1, 0.2)); // number, 0.30000000000000004
print(math.divide(0.3, 0.2)); // number, 1.4999999999999998
console.log();
console.log('no round-off errors with fractions :)');
print(math.add(math.fraction(0.1), math.fraction(0.2))); // Fraction, 3/10
print(math.divide(math.fraction(0.3), math.fraction(0.2))); // Fraction, 3/2
console.log();
console.log('represent an infinite number of repeating digits');
print(math.fraction('1/3')); // Fraction, 0.(3)
print(math.fraction('2/7')); // Fraction, 0.(285714)
print(math.fraction('23/11')); // Fraction, 2.(09)
console.log();
// one can work conveniently with fractions using the expression parser.
// note though that Fractions are only supported by basic arithmetic functions
console.log('use fractions in the expression parser');
printRatio(math.eval('0.1 + 0.2')); // Fraction, 3/10
printRatio(math.eval('0.3 / 0.2')); // Fraction, 3/2
printRatio(math.eval('23 / 11')); // Fraction, 23/11
console.log();
// output formatting
console.log('output formatting of fractions');
var a = math.fraction('2/3');
console.log(math.format(a)); // Fraction, 2/3
console.log(math.format(a, {fraction: 'ratio'})); // Fraction, 2/3
console.log(math.format(a, {fraction: 'decimal'})); // Fraction, 0.(6)
console.log(a.toString()); // Fraction, 0.(6)
console.log();
/**
* Helper function to output a value in the console.
* Fractions will be formatted as ratio, like '1/3'.
* @param {*} value
*/
function printRatio (value) {
console.log(math.format(value, {fraction: 'ratio'}));
}
/**
* Helper function to output a value in the console.
* Fractions will be formatted as decimal, like '0.(3)'.
* @param {*} value
*/
function print (value) {
console.log(math.format(value, {fraction: 'decimal'}));
}

View File

@@ -0,0 +1,101 @@
/**
* Math.js can easily be extended with functions and variables using the
* `import` function. The function `import` accepts a module name or an object
* containing functions and variables.
*/
// load math.js (using node.js)
var math = require('../index');
/**
* Define new functions and variables
*/
math.import({
myConstant: 42,
hello: function (name) {
return 'hello, ' + name + '!';
}
});
// defined methods can be used in both JavaScript as well as the parser
print(math.myConstant * 2); // 84
print(math.hello('user')); // 'hello, user!'
print(math.eval('myConstant + 10')); // 52
print(math.eval('hello("user")')); // 'hello, user!'
/**
* Import the math library numbers.js, https://github.com/sjkaliski/numbers.js
* The library must be installed first using npm:
* npm install numbers
*/
try {
// load the numbers.js library
var numbers = require('numbers');
// import the numbers.js library into math.js
math.import(numbers, {wrap: true, silent: true});
if (math.fibonacci) {
// calculate fibonacci
print(math.fibonacci(7)); // 13
print(math.eval('fibonacci(7)')); // 13
}
}
catch (err) {
console.log('Warning: To import numbers.js, the library must ' +
'be installed first via `npm install numbers`.');
}
/**
* Import the math library numeric.js, http://numericjs.com/
* The library must be installed first using npm:
* npm install numeric
*/
try {
// load the numeric.js library
var numeric = require('numeric');
// import the numeric.js library into math.js
math.import(numeric, {wrap: true, silent: true});
if (math.eig) {
// calculate eigenvalues of a matrix
print(math.eval('eig([1, 2; 4, 3])').lambda.x); // [5, -1];
// solve AX = b
var A = math.eval('[1, 2, 3; 2, -1, 1; 3, 0, -1]');
var b = [9, 8, 3];
print(math.solve(A, b)); // [2, -1, 3]
}
}
catch (err) {
console.log('Warning: To import numeric.js, the library must ' +
'be installed first via `npm install numeric`.');
}
/**
* By default, the function import does not allow overriding existing functions.
* Existing functions can be overridden by specifying option `override: true`
*/
math.import({
pi: 3.14
}, {
override: true
});
print(math.pi); // returns 3.14 instead of 3.141592653589793
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
var precision = 14;
console.log(math.format(value, precision));
}

View File

@@ -0,0 +1,104 @@
// matrices
// load math.js (using node.js)
var math = require('../index');
// create matrices and arrays. a matrix is just a wrapper around an Array,
// providing some handy utilities.
console.log('create a matrix');
var a = math.matrix([1, 4, 9, 16, 25]);
print(a); // [1, 4, 9, 16, 25]
var b = math.matrix(math.ones([2, 3]));
print(b); // [[1, 1, 1], [1, 1, 1]]
print(b.size()); // [2, 3]
// the Array data of a Matrix can be retrieved using valueOf()
var array = a.valueOf();
print(array); // [1, 4, 9, 16, 25]
// Matrices can be cloned
var clone = a.clone();
print(clone); // [1, 4, 9, 16, 25]
console.log();
// perform operations with matrices
console.log('perform operations');
print(math.sqrt(a)); // [1, 2, 3, 4, 5]
var c = [1, 2, 3, 4, 5];
print(math.factorial(c)); // [1, 2, 6, 24, 120]
console.log();
// create and manipulate matrices. Arrays and Matrices can be used mixed.
console.log('manipulate matrices');
var d = [[1, 2], [3, 4]];
print(d); // [[1, 2], [3, 4]]
var e = math.matrix([[5, 6], [1, 1]]);
print(e); // [[5, 6], [1, 1]]
// set a submatrix.
// Matrix indexes are zero-based.
e.subset(math.index(1, [0, 1]), [[7, 8]]);
print(e); // [[5, 6], [7, 8]]
var f = math.multiply(d, e);
print(f); // [[19, 22], [43, 50]]
var g = f.subset(math.index(1, 0));
print(g); // 43
console.log();
// get a sub matrix
// Matrix indexes are zero-based.
console.log('get a sub matrix');
var h = math.diag(math.range(1,4));
print(h); // [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
print(h.subset( math.index([1, 2], [1, 2]))); // [[2, 0], [0, 3]]
var i = math.range(1,6);
print(i); // [1, 2, 3, 4, 5]
print(i.subset(math.index(math.range(1,4)))); // [2, 3, 4]
console.log();
// resize a multi dimensional matrix
console.log('resizing a matrix');
var j = math.matrix();
var defaultValue = 0;
j.resize([2, 2, 2], defaultValue);
print(j); // [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
print(j.size()); // [2, 2, 2]
j.resize([2, 2]);
print(j); // [[0, 0], [0, 0]]
print(j.size()); // [2, 2]
console.log();
// setting a value outside the matrices range will resize the matrix.
// new elements will be initialized with zero.
console.log('set a value outside a matrices range');
var k = math.matrix();
k.subset(math.index(2), 6);
print(k); // [0, 0, 6]
console.log();
console.log('set a value outside a matrices range, leaving new entries uninitialized');
var m = math.matrix();
defaultValue = math.uninitialized;
m.subset(math.index(2), 6, defaultValue);
print(m); // [undefined, undefined, 6]
console.log();
// create ranges
console.log('create ranges');
print(math.range(1, 6)); // [1, 2, 3, 4, 5]
print(math.range(0, 18, 3)); // [0, 3, 6, 9, 12, 15]
print(math.range('2:-1:-3')); // [2, 1, 0, -1, -2]
print(math.factorial(math.range('1:6'))); // [1, 2, 6, 24, 120]
console.log();
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
var precision = 14;
console.log(math.format(value, precision));
}

View File

@@ -0,0 +1,36 @@
// objects
// load math.js (using node.js)
var math = require('../index');
// create an object. Keys can be symbols or strings
print(math.eval('{x: 2 + 1, y: 4}')); // {"x": 3, "y": 4}
print(math.eval('{"name": "John"}')); // {"name": "John"}
// create an object containing an object
print(math.eval('{a: 2, b: {c: 3, d: 4}}')); // {"a": 2, "b": {"c": 3, "d": 4}}
var scope = {
obj: {
prop: 42
}
};
// retrieve properties using dot notation or bracket notation
print(math.eval('obj.prop', scope)); // 42
print(math.eval('obj["prop"]', scope)); // 42
// set properties (returns the whole object, not the property value!)
print(math.eval('obj.prop = 43', scope)); // {"prop": 43}
print(math.eval('obj["prop"] = 43', scope)); // {"prop": 43}
print(scope.obj); // {"prop": 43}
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
var precision = 14;
console.log(math.format(value, precision));
}

View File

@@ -0,0 +1,15 @@
// load math.js (using node.js)
var math = require('../index');
// serialize a math.js data type into a JSON string
var x = math.complex('2+3i');
var str1 = JSON.stringify(x);
console.log(str1);
// outputs {"mathjs":"Complex","re":2,"im":3}
// deserialize a JSON string into a math.js data type
// note that the reviver of math.js is needed for this:
var str2 = '{"mathjs":"Unit","value":5,"unit":"cm"}';
var y = JSON.parse(str2, math.json.reviver);
console.log(math.typeof(y)); // 'Unit'
console.log(y.toString()); // 5 cm

View File

@@ -0,0 +1,18 @@
// load math.js (using node.js)
var math = require('../index');
// create a sparse matrix
console.log('creating a 1000x1000 sparse matrix...');
var a = math.eye(1000, 1000, 'sparse');
// do operations with a sparse matrix
console.log('doing some operations on the sparse matrix...');
var b = math.multiply(a, a);
var c = math.multiply(b, math.complex(2, 2));
var d = math.transpose(c);
var e = math.multiply(d, a);
// we will not print the output, but doing the same operations
// with a dense matrix are very slow, try it for yourself.
console.log('already done');
console.log('now try this with a dense matrix :)');

View File

@@ -0,0 +1,106 @@
// units
// load math.js (using node.js)
var math = require('../index');
// units can be created by providing a value and unit name, or by providing
// a string with a valued unit.
console.log('create units');
var a = math.unit(45, 'cm');
var b = math.unit('0.1m');
print(a); // 450 mm
print(b); // 100 mm
console.log();
// units can be added, subtracted, and multiplied or divided by numbers and by other units
console.log('perform operations');
print(math.add(a, b)); // 0.55 m
print(math.multiply(b, 2)); // 200 mm
print(math.divide(math.unit('1 m'), math.unit('1 s'))); // 1 m / s
print(math.pow(math.unit('12 in'), 3)); // 1728 in^3
console.log();
// units can be converted to a specific type, or to a number
console.log('convert to another type or to a number');
print(b.to('cm')); // 10 cm Alternatively: math.to(b, 'cm')
print(math.to(b, 'inch')); // 3.9370... inch
print(b.toNumber('cm')); // 10
print(math.number(b, 'cm')); // 10
console.log();
// the expression parser supports units too
console.log('parse expressions');
print(math.eval('2 inch to cm')); // 5.08 cm
print(math.eval('cos(45 deg)')); // 0.70711...
print(math.eval('90 km/h to m/s')); // 25 m / s
console.log();
// convert a unit to a number
// A second parameter with the unit for the exported number must be provided
print(math.eval('number(5 cm, mm)')); // number, 50
console.log();
// simplify units
console.log('simplify units');
print(math.eval('100000 N / m^2')); // 100 kPa
print(math.eval('9.81 m/s^2 * 100 kg * 40 m')); // 39.24 kJ
console.log();
// example engineering calculations
console.log('compute molar volume of ideal gas at 65 Fahrenheit, 14.7 psi in L/mol');
var Rg = math.unit('8.314 N m / (mol K)');
var T = math.unit('65 degF');
var P = math.unit('14.7 psi');
var v = math.divide(math.multiply(Rg, T), P);
console.log('gas constant (Rg) = ', format(Rg));
console.log('P = ' + format(P));
console.log('T = ' + format(T));
console.log('v = Rg * T / P = ' + format(math.to(v, 'L/mol'))); // 23.910... L / mol
console.log();
console.log('compute speed of fluid flowing out of hole in a container');
var g = math.unit('9.81 m / s^2');
var h = math.unit('1 m');
var v = math.pow(math.multiply(2, math.multiply(g, h)), 0.5); // Can also use math.sqrt
console.log('g = ' + format(g));
console.log('h = ' + format(h));
console.log('v = (2 g h) ^ 0.5 = ' + format(v)); // 4.429... m / s
console.log();
console.log('electrical power consumption:');
var expr = '460 V * 20 A * 30 days to kWh';
console.log(expr + ' = ' + math.eval(expr)); // 6624 kWh
console.log();
console.log('circuit design:');
var expr = '24 V / (6 mA)';
console.log(expr + ' = ' + math.eval(expr)); // 4 kohm
console.log();
console.log('operations on arrays:');
var B = math.eval('[1, 0, 0] T');
var v = math.eval('[0, 1, 0] m/s');
var q = math.eval('1 C');
var F = math.multiply(q, math.cross(v, B));
console.log('B (magnetic field strength) = ' + format(B)); // [1 T, 0 T, 0 T]
console.log('v (particle velocity) = ' + format(v)); // [0 m / s, 1 m / s, 0 m / s]
console.log('q (particle charge) = ' + format(q)); // 1 C
console.log('F (force) = q (v cross B) = ' + format(F)); // [0 N, 0 N, -1 N]
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
console.log(format(value));
}
/**
* Helper function to format an output a value.
* @param {*} value
* @return {string} Returns the formatted value
*/
function format (value) {
var precision = 14;
return math.format(value, precision);
}