mirror of
https://github.com/josdejong/mathjs.git
synced 2026-01-25 15:07:57 +00:00
Added examples to website. Updated docs.
This commit is contained in:
parent
be9173526b
commit
7ec04ef0dd
@ -52,6 +52,11 @@
|
||||
{% if page.url contains '/docs/' and page.url != '/docs/getting_started.html' %}
|
||||
<div class="selection"></div>
|
||||
{% endif %}
|
||||
</a><a href="/examples/index.html">
|
||||
Examples
|
||||
{% if page.url contains '/examples/' %}
|
||||
<div class="selection"></div>
|
||||
{% endif %}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@ -78,7 +83,7 @@
|
||||
|
||||
var page = document.getElementById('page');
|
||||
page.className = (width < 810) ? 'small' : 'normal';
|
||||
if (width < 500) {
|
||||
if (width < 620) {
|
||||
page.className += ' tiny';
|
||||
}
|
||||
|
||||
|
||||
@ -11,7 +11,8 @@
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.highlight .c1 {
|
||||
.highlight .c1,
|
||||
.highlight .cm {
|
||||
color: #808080;
|
||||
}
|
||||
|
||||
|
||||
@ -64,7 +64,7 @@ body {
|
||||
display: inline-block;
|
||||
border-right: 2px solid #f5f5f5;
|
||||
font-weight: bold;
|
||||
padding: 10px 20px;
|
||||
padding: 10px 18px;
|
||||
margin: 0;
|
||||
position: relative;
|
||||
text-decoration: none;
|
||||
|
||||
@ -10,9 +10,10 @@ from the command line. To install math.js globally:
|
||||
npm install -g mathjs
|
||||
|
||||
Normally, a global installation must be run with admin rights (precede the
|
||||
command with `sudo`). After installation, the application `mathjs` is available:
|
||||
command with `sudo`). After installation, the application `mathjs` is available
|
||||
via the command line:
|
||||
|
||||
```sh
|
||||
```bash
|
||||
$ mathjs
|
||||
> 12 / (2.3 + 0.7)
|
||||
4
|
||||
@ -29,10 +30,10 @@ $ mathjs
|
||||
The command line interface can be used to open a prompt, to execute a script,
|
||||
or to pipe input and output streams:
|
||||
|
||||
```sh
|
||||
```bash
|
||||
$ mathjs # Open a command prompt
|
||||
$ mathjs script.txt # Run a script file
|
||||
$ mathjs script.txt # Run a script file, output to console
|
||||
$ mathjs script.txt > results.txt # Run a script file, output to file
|
||||
$ cat script.txt | mathjs # Run input stream
|
||||
$ cat script.txt | mathjs # Run input stream, output to console
|
||||
$ cat script.txt | mathjs > results.txt # Run input stream, output to file
|
||||
```
|
||||
|
||||
@ -51,30 +51,34 @@ This section shows a number of configuration examples.
|
||||
var math = require('mathjs');
|
||||
|
||||
// range will output a Matrix
|
||||
math.range(0, 4); // Matrix [0, 1, 2, 3]
|
||||
math.range(0, 4); // Matrix [0, 1, 2, 3]
|
||||
|
||||
|
||||
// create a new instance configured to use Arrays
|
||||
var math2 = math({matrix: 'Array'});
|
||||
var math2 = math({
|
||||
matrix: 'array' // Choose 'matrix' (default) or 'array'
|
||||
});
|
||||
|
||||
// range will output an Array
|
||||
math2.range(0, 4); // Array [0, 1, 2, 3]
|
||||
math2.range(0, 4); // Array [0, 1, 2, 3]
|
||||
|
||||
// change the configuration of math2 from Arrays to Matrices
|
||||
math2.config({matrix: 'matrix'});
|
||||
math2.config({
|
||||
matrix: 'matrix' // Choose 'matrix' (default) or 'array'
|
||||
});
|
||||
|
||||
// range will output a Matrix
|
||||
math2.range(0, 4); // Matrix [0, 1, 2, 3]
|
||||
math2.range(0, 4); // Matrix [0, 1, 2, 3]
|
||||
|
||||
|
||||
// create an instance of math.js with bignumber configuration
|
||||
var bigmath = math({
|
||||
number: 'bignumber',
|
||||
precision: 128
|
||||
number: 'bignumber', // Choose 'number' (default) or 'bignumber'
|
||||
precision: 32 // 64 by default, only applicable for BigNumbers
|
||||
});
|
||||
|
||||
// parser will parse numbers as BigNumber now:
|
||||
bigmath.eval('1 / 3'); // BigNumber, 0.33333333333333333333333333333333
|
||||
bigmath.eval('1 / 3'); // BigNumber, 0.33333333333333333333333333333333
|
||||
```
|
||||
|
||||
### browser
|
||||
@ -91,24 +95,25 @@ bigmath.eval('1 / 3'); // BigNumber, 0.33333333333333333333333333333333
|
||||
// the default instance of math.js is available as 'math'
|
||||
|
||||
// range will output a Matrix
|
||||
math.range(0, 4); // Matrix [0, 1, 2, 3]
|
||||
math.range(0, 4); // Matrix [0, 1, 2, 3]
|
||||
|
||||
// change the configuration of math from Arrays to Matrices
|
||||
math.config({matrix: 'matrix'});
|
||||
// change the configuration of math from Matrices to Arrays
|
||||
math.config({
|
||||
matrix: 'array' // Choose 'matrix' (default) or 'array'
|
||||
});
|
||||
|
||||
// range will output an Array
|
||||
math.range(0, 4); // Array [0, 1, 2, 3]
|
||||
math.range(0, 4); // Array [0, 1, 2, 3]
|
||||
|
||||
// create a new instance of math.js with bignumber configuration
|
||||
var bigmath = math({
|
||||
number: 'bignumber',
|
||||
precision: 128
|
||||
number: 'bignumber', // Choose 'number' (default) or 'bignumber'
|
||||
precision: 32 // 64 by default, only applicable for BigNumbers
|
||||
});
|
||||
|
||||
// parser will parse numbers as BigNumber now:
|
||||
bigmath.eval('1 / 3'); // BigNumber, 0.33333333333333333333333333333333
|
||||
bigmath.eval('1 / 3'); // BigNumber, 0.33333333333333333333333333333333
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
```
|
||||
|
||||
@ -9,11 +9,13 @@ This getting started describes how to install, load, and use math.js.
|
||||
|
||||
## Install
|
||||
|
||||
Math.js can be installed using various package managers like [npm](https://npmjs.org/) and [bower](http://twitter.github.io/bower/), or by just downloading the library. To install via npm, run:
|
||||
Math.js can be installed using various package managers like [npm](https://npmjs.org/) and [bower](http://twitter.github.io/bower/), or by just downloading the library from the website: [http://mathjs.org/download.html](http://mathjs.org/download.html).
|
||||
|
||||
To install via npm, run:
|
||||
|
||||
npm install mathjs
|
||||
|
||||
Other ways to install math.js and downloads are available on the website: [http://mathjs.org/download.html](http://mathjs.org/download.html).
|
||||
Other ways to install math.js are described on the [website](http://mathjs.org/download.html).
|
||||
|
||||
|
||||
## Load
|
||||
@ -38,7 +40,7 @@ math.sqrt(-4); // 2i
|
||||
|
||||
### Browser
|
||||
|
||||
Math.js can be loaded as a regular javascript file in the browser:
|
||||
Math.js can be loaded as a regular JavaScript file in the browser:
|
||||
|
||||
```html
|
||||
<!DOCTYPE HTML>
|
||||
|
||||
@ -47,7 +47,6 @@ layout: default
|
||||
- [format(value [, precision])](format.html)
|
||||
- [gcd(a, b)](gcd.html)
|
||||
- [help(search)](help.html)
|
||||
- [ifElse(condition, trueExpr, falseExpr)](ifElse.html)
|
||||
- [im(x)](im.html)
|
||||
- [import(filename | object, override)](import.html)
|
||||
- [index(range1, range2, ...)](index.html)
|
||||
|
||||
@ -137,7 +137,6 @@ layout: default
|
||||
- [clone(x)](clone.html)
|
||||
- [forEach(x, callback)](forEach.html)
|
||||
- [format(value [, precision])](format.html)
|
||||
- [ifElse(condition, trueExpr, falseExpr)](ifElse.html)
|
||||
- [import(filename | object, override)](import.html)
|
||||
- [map(x, callback)](map.html)
|
||||
- [print(template, values [, precision])](print.html)
|
||||
|
||||
@ -1,40 +0,0 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Function ifElse
|
||||
|
||||
Execute a conditional expression.
|
||||
|
||||
|
||||
## Syntax
|
||||
|
||||
```js
|
||||
math.ifElse(condition, trueExpr, falseExpr)
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
Parameter | Type | Description
|
||||
--------- | ---- | -----------
|
||||
`condition` | Number | Boolean | String | Complex | BigNumber | Unit | The conditional expression
|
||||
`trueExpr` | * | The true expression
|
||||
`falseExpr` | * | The false expression
|
||||
|
||||
### Returns
|
||||
|
||||
Type | Description
|
||||
---- | -----------
|
||||
* | The evaluated return expression
|
||||
|
||||
|
||||
## Examples
|
||||
|
||||
```js
|
||||
math.ifElse(true, 'yes', 'no'); // returns 'yes'
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
|
||||
@ -27,7 +27,7 @@ Math.js can be downloaded or linked from [cdnjs](http://cdnjs.com/):
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<span id="development-size">696 kB</span>, uncompressed with comments
|
||||
<span id="development-size">692 kB</span>, uncompressed with comments
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
|
||||
58
examples/basic_usage.md
Normal file
58
examples/basic_usage.md
Normal file
@ -0,0 +1,58 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Basic usage
|
||||
|
||||
Raw file: [basic_usage.js](raw/basic_usage.js)
|
||||
|
||||
```js
|
||||
// basic usage
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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]]
|
||||
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.select(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();
|
||||
```
|
||||
48
examples/bignumbers.md
Normal file
48
examples/bignumbers.md
Normal file
@ -0,0 +1,48 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Bignumbers
|
||||
|
||||
Raw file: [bignumbers.js](raw/bignumbers.js)
|
||||
|
||||
```js
|
||||
// BigNumbers
|
||||
|
||||
// load math.js
|
||||
// the default type of numbers is configured as BigNumbers
|
||||
var math = require('../index')({
|
||||
number: 'bignumber', // Default type of number: 'number' (default) or 'bignumber'
|
||||
precision: 20 // Number of significant digits for BigNumbers
|
||||
});
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
console.log(math.format(value));
|
||||
}
|
||||
|
||||
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();
|
||||
```
|
||||
140
examples/browser_angle_configuration.md
Normal file
140
examples/browser_angle_configuration.md
Normal file
@ -0,0 +1,140 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Angle configuration
|
||||
|
||||
Raw file: [angle_configuration.html](raw/browser/angle_configuration.html)
|
||||
|
||||
```html
|
||||
<!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 type="text/javascript" src="/js/lib/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
|
||||
|
||||
replacements[name] = function replacement(x) {
|
||||
if (x instanceof math.type.BigNumber) {
|
||||
x = x.toNumber(); // convert to number
|
||||
}
|
||||
|
||||
if (typeof x === 'boolean') {
|
||||
x = +x; // convert to number
|
||||
}
|
||||
|
||||
if (typeof x === 'number') {
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
if (math.collection.isCollection(x)) {
|
||||
return math.collection.deepMap(x, replacement);
|
||||
}
|
||||
|
||||
return fn(x);
|
||||
};
|
||||
});
|
||||
|
||||
// create trigonometric functions replacing the output depending on angle config
|
||||
['asin', 'acos', 'atan', 'atan2'].forEach(function(name) {
|
||||
var fn = math[name]; // the original function
|
||||
|
||||
replacements[name] = function replacement(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;
|
||||
}
|
||||
}
|
||||
|
||||
if (math.collection.isCollection(x)) {
|
||||
return math.collection.deepMap(x, replacement);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
});
|
||||
|
||||
// import all replacements into math.js, override existing trigonometric functions
|
||||
math.import(replacements, {override: true, wrap: false});
|
||||
|
||||
// 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>```
|
||||
46
examples/browser_basic_usage.md
Normal file
46
examples/browser_basic_usage.md
Normal file
@ -0,0 +1,46 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Basic usage
|
||||
|
||||
Raw file: [basic_usage.html](raw/browser/basic_usage.html)
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>math.js | basic usage</title>
|
||||
<script type="text/javascript" src="/js/lib/math.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<script>
|
||||
function print(value) {
|
||||
var precision = 5;
|
||||
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.select(3)
|
||||
.add(4)
|
||||
.multiply(2)
|
||||
.done();
|
||||
print(a); // 14
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>```
|
||||
89
examples/browser_custom_separators.md
Normal file
89
examples/browser_custom_separators.md
Normal file
@ -0,0 +1,89 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Custom separators
|
||||
|
||||
Raw file: [custom_separators.html](raw/browser/custom_separators.html)
|
||||
|
||||
```html
|
||||
<!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 type="text/javascript" src="/js/lib/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>```
|
||||
56
examples/browser_old_browsers.md
Normal file
56
examples/browser_old_browsers.md
Normal file
@ -0,0 +1,56 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Old browsers
|
||||
|
||||
Raw file: [old_browsers.html](raw/browser/old_browsers.html)
|
||||
|
||||
```html
|
||||
<!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 type="text/javascript" src="/js/lib/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 = 5;
|
||||
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.select(3)
|
||||
.add(4)
|
||||
.multiply(2)
|
||||
.done();
|
||||
print(a); // 14
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>```
|
||||
113
examples/browser_pretty_printing_with_mathjax.md
Normal file
113
examples/browser_pretty_printing_with_mathjax.md
Normal file
@ -0,0 +1,113 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Pretty printing with mathjax
|
||||
|
||||
Raw file: [pretty_printing_with_mathjax.html](raw/browser/pretty_printing_with_mathjax.html)
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>math.js | pretty printing with MathJax</title>
|
||||
|
||||
<script src="/js/lib/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>```
|
||||
28
examples/browser_requirejs_loading.md
Normal file
28
examples/browser_requirejs_loading.md
Normal file
@ -0,0 +1,28 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Requirejs loading
|
||||
|
||||
Raw file: [requirejs_loading.html](raw/browser/requirejs_loading.html)
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>math.js | require.js loading</title>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.11/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>```
|
||||
68
examples/chained_operations.md
Normal file
68
examples/chained_operations.md
Normal file
@ -0,0 +1,68 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Chained operations
|
||||
|
||||
Raw file: [chained_operations.js](raw/chained_operations.js)
|
||||
|
||||
```js
|
||||
// chained operations
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// create a chained operation using the function select
|
||||
// end a chain using done().
|
||||
var a = math.select(3)
|
||||
.add(4)
|
||||
.multiply(2)
|
||||
.done();
|
||||
print(a); // 14
|
||||
|
||||
// all functions and variables available in the math namespace can be used
|
||||
// from a selector
|
||||
var b = math.select()
|
||||
.pi
|
||||
.divide(4)
|
||||
.sin()
|
||||
.square()
|
||||
.done();
|
||||
print(b); // 0.5
|
||||
|
||||
// A selector 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 selectors value
|
||||
var selector = math.select(2).divide(3);
|
||||
var str = selector.toString();
|
||||
print(str); // "0.6666666666666666"
|
||||
|
||||
// a selector has a .valueOf(), which returns the value hold by the selector.
|
||||
// This allows using it in regular operations. The function valueOf() acts the
|
||||
// same as function done().
|
||||
print(selector.valueOf()); // 0.66667
|
||||
print(selector + 2); // 2.66667
|
||||
|
||||
// the function subset can be used to get or replace sub matrices
|
||||
var array = [[1, 2], [3, 4]];
|
||||
var v = math.select(array)
|
||||
.subset(math.index(1, 0))
|
||||
.done();
|
||||
print(v); // 3
|
||||
|
||||
var m = math.select(array)
|
||||
.subset(math.index(0, 0), 8)
|
||||
.multiply(3)
|
||||
.done();
|
||||
print(m); // [[24, 6], [9, 12]]
|
||||
```
|
||||
64
examples/complex_numbers.md
Normal file
64
examples/complex_numbers.md
Normal file
@ -0,0 +1,64 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Complex numbers
|
||||
|
||||
Raw file: [complex_numbers.js](raw/complex_numbers.js)
|
||||
|
||||
```js
|
||||
// complex numbers
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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.6541 + 2.8417i
|
||||
|
||||
// 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.toPolar()); // { r: 5, phi: 0.9272952180016122 }
|
||||
```
|
||||
202
examples/expressions.md
Normal file
202
examples/expressions.md
Normal file
@ -0,0 +1,202 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Expressions
|
||||
|
||||
Raw file: [expressions.js](raw/expressions.js)
|
||||
|
||||
```js
|
||||
/**
|
||||
* 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
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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 the node
|
||||
var code1 = node1.compile(math);
|
||||
|
||||
// evaluate the compiled code
|
||||
print(code1.eval()); // 5
|
||||
|
||||
// provide a scope
|
||||
console.log('\nprovide a scope');
|
||||
var node2 = math.parse('x^a');
|
||||
var code2 = node2.compile(math);
|
||||
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();
|
||||
```
|
||||
101
examples/import.md
Normal file
101
examples/import.md
Normal file
@ -0,0 +1,101 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Import
|
||||
|
||||
Raw file: [import.js](raw/import.js)
|
||||
|
||||
```js
|
||||
/**
|
||||
* 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
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
// import the numbers.js library into math.js
|
||||
math.import('numbers');
|
||||
}
|
||||
catch (err) {
|
||||
console.log('Warning: to import numbers.js, the library must\n' +
|
||||
'be installed first via `npm install numbers`.');
|
||||
}
|
||||
|
||||
if (math.fibonacci) {
|
||||
// calculate fibonacci
|
||||
print(math.fibonacci(7)); // 13
|
||||
print(math.eval('fibonacci(7)')); // 13
|
||||
}
|
||||
|
||||
/**
|
||||
* Import the math library numeric.js, http://numericjs.com/
|
||||
* The library must be installed first using npm:
|
||||
* npm install numeric
|
||||
*/
|
||||
try {
|
||||
// import the numeric.js library into math.js
|
||||
math.import('numeric');
|
||||
}
|
||||
catch (err) {
|
||||
console.log('Warning: to import numeric.js, the library must\n' +
|
||||
'be installed first via `npm install numeric`.');
|
||||
}
|
||||
|
||||
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]
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
```
|
||||
23
examples/index.md
Normal file
23
examples/index.md
Normal file
@ -0,0 +1,23 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Examples
|
||||
|
||||
- [Basic usage](basic_usage.html)
|
||||
- [Bignumbers](bignumbers.html)
|
||||
- [Chained operations](chained_operations.html)
|
||||
- [Complex numbers](complex_numbers.html)
|
||||
- [Expressions](expressions.html)
|
||||
- [Import](import.html)
|
||||
- [Matrices](matrices.html)
|
||||
- [Units](units.html)
|
||||
|
||||
# Browser examples
|
||||
|
||||
- [Angle configuration](browser_angle_configuration.html)
|
||||
- [Basic usage](browser_basic_usage.html)
|
||||
- [Custom separators](browser_custom_separators.html)
|
||||
- [Old browsers](browser_old_browsers.html)
|
||||
- [Pretty printing with mathjax](browser_pretty_printing_with_mathjax.html)
|
||||
- [Requirejs loading](browser_requirejs_loading.html)
|
||||
108
examples/matrices.md
Normal file
108
examples/matrices.md
Normal file
@ -0,0 +1,108 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Matrices
|
||||
|
||||
Raw file: [matrices.js](raw/matrices.js)
|
||||
|
||||
```js
|
||||
// matrices
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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, 2]), [[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, 3], [1, 3])));// [[2, 0], [0, 3]]
|
||||
console.log();
|
||||
|
||||
// resize a multi dimensional matrix
|
||||
console.log('resizing a matrix');
|
||||
var i = math.matrix();
|
||||
var defaultValue = 0;
|
||||
i.resize([2, 2, 2], defaultValue);
|
||||
print(i); // [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
||||
print(i.size()); // [2, 2, 2]
|
||||
i.resize([2, 2]);
|
||||
print(i); // [[0, 0], [0, 0]]
|
||||
print(i.size()); // [2, 2]
|
||||
console.log();
|
||||
|
||||
// setting a value outside the matrices range will resize the matrix.
|
||||
// new elements will be initialized with undefined.
|
||||
console.log('set a value outside a matrices range');
|
||||
var j = math.matrix();
|
||||
j.subset(math.index(2), 6);
|
||||
print(j); // [undefined, undefined, 6]
|
||||
console.log();
|
||||
|
||||
console.log('set a value outside a matrices range providing a default value');
|
||||
var k = math.matrix();
|
||||
defaultValue = 0;
|
||||
k.subset(math.index(2), 6, defaultValue);
|
||||
print(k); // [0, 0, 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();
|
||||
```
|
||||
48
examples/raw/basic_usage.js
Normal file
48
examples/raw/basic_usage.js
Normal file
@ -0,0 +1,48 @@
|
||||
// basic usage
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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]]
|
||||
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.select(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();
|
||||
38
examples/raw/bignumbers.js
Normal file
38
examples/raw/bignumbers.js
Normal file
@ -0,0 +1,38 @@
|
||||
// BigNumbers
|
||||
|
||||
// load math.js
|
||||
// the default type of numbers is configured as BigNumbers
|
||||
var math = require('../index')({
|
||||
number: 'bignumber', // Default type of number: 'number' (default) or 'bignumber'
|
||||
precision: 20 // Number of significant digits for BigNumbers
|
||||
});
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
console.log(math.format(value));
|
||||
}
|
||||
|
||||
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();
|
||||
131
examples/raw/browser/angle_configuration.html
Normal file
131
examples/raw/browser/angle_configuration.html
Normal file
@ -0,0 +1,131 @@
|
||||
<!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 type="text/javascript" src="/js/lib/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
|
||||
|
||||
replacements[name] = function replacement(x) {
|
||||
if (x instanceof math.type.BigNumber) {
|
||||
x = x.toNumber(); // convert to number
|
||||
}
|
||||
|
||||
if (typeof x === 'boolean') {
|
||||
x = +x; // convert to number
|
||||
}
|
||||
|
||||
if (typeof x === 'number') {
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
if (math.collection.isCollection(x)) {
|
||||
return math.collection.deepMap(x, replacement);
|
||||
}
|
||||
|
||||
return fn(x);
|
||||
};
|
||||
});
|
||||
|
||||
// create trigonometric functions replacing the output depending on angle config
|
||||
['asin', 'acos', 'atan', 'atan2'].forEach(function(name) {
|
||||
var fn = math[name]; // the original function
|
||||
|
||||
replacements[name] = function replacement(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;
|
||||
}
|
||||
}
|
||||
|
||||
if (math.collection.isCollection(x)) {
|
||||
return math.collection.deepMap(x, replacement);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
});
|
||||
|
||||
// import all replacements into math.js, override existing trigonometric functions
|
||||
math.import(replacements, {override: true, wrap: false});
|
||||
|
||||
// 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>
|
||||
37
examples/raw/browser/basic_usage.html
Normal file
37
examples/raw/browser/basic_usage.html
Normal file
@ -0,0 +1,37 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>math.js | basic usage</title>
|
||||
<script type="text/javascript" src="/js/lib/math.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<script>
|
||||
function print(value) {
|
||||
var precision = 5;
|
||||
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.select(3)
|
||||
.add(4)
|
||||
.multiply(2)
|
||||
.done();
|
||||
print(a); // 14
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
80
examples/raw/browser/custom_separators.html
Normal file
80
examples/raw/browser/custom_separators.html
Normal 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 type="text/javascript" src="/js/lib/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>
|
||||
47
examples/raw/browser/old_browsers.html
Normal file
47
examples/raw/browser/old_browsers.html
Normal 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 type="text/javascript" src="/js/lib/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 = 5;
|
||||
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.select(3)
|
||||
.add(4)
|
||||
.multiply(2)
|
||||
.done();
|
||||
print(a); // 14
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
104
examples/raw/browser/pretty_printing_with_mathjax.html
Normal file
104
examples/raw/browser/pretty_printing_with_mathjax.html
Normal file
@ -0,0 +1,104 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>math.js | pretty printing with MathJax</title>
|
||||
|
||||
<script src="/js/lib/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>
|
||||
19
examples/raw/browser/requirejs_loading.html
Normal file
19
examples/raw/browser/requirejs_loading.html
Normal 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.11/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>
|
||||
79
examples/raw/browser/webworkers/webworkers.html
Normal file
79
examples/raw/browser/webworkers/webworkers.html
Normal 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>
|
||||
30
examples/raw/browser/webworkers/worker.js
Normal file
30
examples/raw/browser/webworkers/worker.js
Normal 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);
|
||||
58
examples/raw/chained_operations.js
Normal file
58
examples/raw/chained_operations.js
Normal file
@ -0,0 +1,58 @@
|
||||
// chained operations
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// create a chained operation using the function select
|
||||
// end a chain using done().
|
||||
var a = math.select(3)
|
||||
.add(4)
|
||||
.multiply(2)
|
||||
.done();
|
||||
print(a); // 14
|
||||
|
||||
// all functions and variables available in the math namespace can be used
|
||||
// from a selector
|
||||
var b = math.select()
|
||||
.pi
|
||||
.divide(4)
|
||||
.sin()
|
||||
.square()
|
||||
.done();
|
||||
print(b); // 0.5
|
||||
|
||||
// A selector 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 selectors value
|
||||
var selector = math.select(2).divide(3);
|
||||
var str = selector.toString();
|
||||
print(str); // "0.6666666666666666"
|
||||
|
||||
// a selector has a .valueOf(), which returns the value hold by the selector.
|
||||
// This allows using it in regular operations. The function valueOf() acts the
|
||||
// same as function done().
|
||||
print(selector.valueOf()); // 0.66667
|
||||
print(selector + 2); // 2.66667
|
||||
|
||||
// the function subset can be used to get or replace sub matrices
|
||||
var array = [[1, 2], [3, 4]];
|
||||
var v = math.select(array)
|
||||
.subset(math.index(1, 0))
|
||||
.done();
|
||||
print(v); // 3
|
||||
|
||||
var m = math.select(array)
|
||||
.subset(math.index(0, 0), 8)
|
||||
.multiply(3)
|
||||
.done();
|
||||
print(m); // [[24, 6], [9, 12]]
|
||||
54
examples/raw/complex_numbers.js
Normal file
54
examples/raw/complex_numbers.js
Normal file
@ -0,0 +1,54 @@
|
||||
// complex numbers
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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.6541 + 2.8417i
|
||||
|
||||
// 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.toPolar()); // { r: 5, phi: 0.9272952180016122 }
|
||||
192
examples/raw/expressions.js
Normal file
192
examples/raw/expressions.js
Normal file
@ -0,0 +1,192 @@
|
||||
/**
|
||||
* 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
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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 the node
|
||||
var code1 = node1.compile(math);
|
||||
|
||||
// evaluate the compiled code
|
||||
print(code1.eval()); // 5
|
||||
|
||||
// provide a scope
|
||||
console.log('\nprovide a scope');
|
||||
var node2 = math.parse('x^a');
|
||||
var code2 = node2.compile(math);
|
||||
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();
|
||||
91
examples/raw/import.js
Normal file
91
examples/raw/import.js
Normal file
@ -0,0 +1,91 @@
|
||||
/**
|
||||
* 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
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
// import the numbers.js library into math.js
|
||||
math.import('numbers');
|
||||
}
|
||||
catch (err) {
|
||||
console.log('Warning: to import numbers.js, the library must\n' +
|
||||
'be installed first via `npm install numbers`.');
|
||||
}
|
||||
|
||||
if (math.fibonacci) {
|
||||
// calculate fibonacci
|
||||
print(math.fibonacci(7)); // 13
|
||||
print(math.eval('fibonacci(7)')); // 13
|
||||
}
|
||||
|
||||
/**
|
||||
* Import the math library numeric.js, http://numericjs.com/
|
||||
* The library must be installed first using npm:
|
||||
* npm install numeric
|
||||
*/
|
||||
try {
|
||||
// import the numeric.js library into math.js
|
||||
math.import('numeric');
|
||||
}
|
||||
catch (err) {
|
||||
console.log('Warning: to import numeric.js, the library must\n' +
|
||||
'be installed first via `npm install numeric`.');
|
||||
}
|
||||
|
||||
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]
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
98
examples/raw/matrices.js
Normal file
98
examples/raw/matrices.js
Normal file
@ -0,0 +1,98 @@
|
||||
// matrices
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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, 2]), [[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, 3], [1, 3])));// [[2, 0], [0, 3]]
|
||||
console.log();
|
||||
|
||||
// resize a multi dimensional matrix
|
||||
console.log('resizing a matrix');
|
||||
var i = math.matrix();
|
||||
var defaultValue = 0;
|
||||
i.resize([2, 2, 2], defaultValue);
|
||||
print(i); // [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]
|
||||
print(i.size()); // [2, 2, 2]
|
||||
i.resize([2, 2]);
|
||||
print(i); // [[0, 0], [0, 0]]
|
||||
print(i.size()); // [2, 2]
|
||||
console.log();
|
||||
|
||||
// setting a value outside the matrices range will resize the matrix.
|
||||
// new elements will be initialized with undefined.
|
||||
console.log('set a value outside a matrices range');
|
||||
var j = math.matrix();
|
||||
j.subset(math.index(2), 6);
|
||||
print(j); // [undefined, undefined, 6]
|
||||
console.log();
|
||||
|
||||
console.log('set a value outside a matrices range providing a default value');
|
||||
var k = math.matrix();
|
||||
defaultValue = 0;
|
||||
k.subset(math.index(2), 6, defaultValue);
|
||||
print(k); // [0, 0, 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();
|
||||
41
examples/raw/units.js
Normal file
41
examples/raw/units.js
Normal file
@ -0,0 +1,41 @@
|
||||
// units
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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
|
||||
console.log('perform operations');
|
||||
print(math.add(a, b)); // 0.55 m
|
||||
print(math.multiply(b, 2)); // 200 mm
|
||||
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.937 inch
|
||||
print(b.toNumber('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
|
||||
console.log();
|
||||
51
examples/units.md
Normal file
51
examples/units.md
Normal file
@ -0,0 +1,51 @@
|
||||
---
|
||||
layout: default
|
||||
---
|
||||
|
||||
# Units
|
||||
|
||||
Raw file: [units.js](raw/units.js)
|
||||
|
||||
```js
|
||||
// units
|
||||
|
||||
// load math.js
|
||||
var math = require('../index');
|
||||
|
||||
/**
|
||||
* Helper function to output a value in the console. Value will be formatted.
|
||||
* @param {*} value
|
||||
*/
|
||||
function print (value) {
|
||||
var precision = 5;
|
||||
console.log(math.format(value, precision));
|
||||
}
|
||||
|
||||
// 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
|
||||
console.log('perform operations');
|
||||
print(math.add(a, b)); // 0.55 m
|
||||
print(math.multiply(b, 2)); // 200 mm
|
||||
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.937 inch
|
||||
print(b.toNumber('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
|
||||
console.log();
|
||||
```
|
||||
111
gulpfile.js
111
gulpfile.js
@ -1,21 +1,28 @@
|
||||
var exec = require('child_process').exec;
|
||||
var fs = require('fs');
|
||||
var path = require('path');
|
||||
var zlib = require('zlib');
|
||||
var glob = require('glob');
|
||||
var rimraf = require('rimraf');
|
||||
var gulp = require('gulp');
|
||||
var gutil = require('gulp-util');
|
||||
var replace = require('gulp-replace');
|
||||
var rename = require('gulp-rename');
|
||||
var header = require('gulp-header');
|
||||
var handlebars = require('handlebars');
|
||||
|
||||
var LIB_SRC = './node_modules/mathjs/dist/*';
|
||||
var LIB_DEST = './js/lib';
|
||||
var DOCS_SRC = './node_modules/mathjs/docs/**/*.md';
|
||||
var DOCS_DEST = './docs';
|
||||
var HISTORY_SRC = './node_modules/mathjs/HISTORY.md';
|
||||
var HISTORY_DEST = '.';
|
||||
var MATHJS = './js/lib/math.js';
|
||||
var MATHJS_MIN = './js/lib/math.min.js';
|
||||
var DOWNLOAD = './download.md';
|
||||
var LIB_SRC = './node_modules/mathjs/dist/*';
|
||||
var LIB_DEST = './js/lib';
|
||||
var DOCS_SRC = './node_modules/mathjs/docs/**/*.md';
|
||||
var DOCS_DEST = './docs';
|
||||
var EXAMPLES_SRC = './node_modules/mathjs/examples/**/*';
|
||||
var EXAMPLES_DEST = './examples';
|
||||
var EXAMPLES_RAW_DEST = EXAMPLES_DEST + '/raw';
|
||||
var HISTORY_SRC = './node_modules/mathjs/HISTORY.md';
|
||||
var HISTORY_DEST = '.';
|
||||
var MATHJS = LIB_DEST + '/math.js';
|
||||
var MATHJS_MIN = LIB_DEST + '/math.min.js';
|
||||
var DOWNLOAD = './download.md';
|
||||
|
||||
var MD_HEADER =
|
||||
'---\n' +
|
||||
@ -23,6 +30,24 @@ var MD_HEADER =
|
||||
'---\n' +
|
||||
'\n';
|
||||
|
||||
var EXAMPLE_TEMPLATE = MD_HEADER +
|
||||
'# {{title}}\n\n' +
|
||||
'Raw file: [{{filename}}]({{path}})\n\n' +
|
||||
'```{{type}}\n' +
|
||||
'{{{code}}}' +
|
||||
'```\n';
|
||||
|
||||
var INDEX_TEMPLATE = MD_HEADER +
|
||||
'# Examples\n\n' +
|
||||
'{{#each files}}' +
|
||||
'- [{{title}}]({{page}})\n' +
|
||||
'{{/each}}' +
|
||||
'\n' +
|
||||
'# Browser examples\n\n' +
|
||||
'{{#each browserFiles}}' +
|
||||
'- [{{title}}]({{page}})\n' +
|
||||
'{{/each}}';
|
||||
|
||||
/**
|
||||
* Update the dependencies (mathjs) to the latest version
|
||||
*/
|
||||
@ -51,6 +76,72 @@ gulp.task('docs', ['update'], function () {
|
||||
.pipe(gulp.dest(DOCS_DEST));
|
||||
});
|
||||
|
||||
/**
|
||||
* Clean all examples
|
||||
*/
|
||||
gulp.task('cleanExamples', function (cb) {
|
||||
rimraf(EXAMPLES_DEST, cb);
|
||||
});
|
||||
|
||||
/**
|
||||
* Copy all examples
|
||||
*/
|
||||
gulp.task('copyExamples', ['update', 'cleanExamples'], function () {
|
||||
return gulp.src(EXAMPLES_SRC)
|
||||
.pipe(replace(/src=".*dist\/math.js"/, 'src="/js/lib/math.js"'))
|
||||
.pipe(replace(/src=".*dist\/math.min.js"/, 'src="/js/lib/math.min.js"'))
|
||||
.pipe(gulp.dest(EXAMPLES_RAW_DEST));
|
||||
});
|
||||
|
||||
/**
|
||||
* Create markdown pages for every example
|
||||
*/
|
||||
gulp.task('examples', ['update', 'copyExamples'], function (cb) {
|
||||
var template = handlebars.compile(EXAMPLE_TEMPLATE);
|
||||
|
||||
function generate(pattern, callback) {
|
||||
glob(EXAMPLES_RAW_DEST + '/' + pattern, function (err, files) {
|
||||
var results = files.map(function (file) {
|
||||
var relative = path.relative(EXAMPLES_RAW_DEST, file);
|
||||
var prefix = path.dirname(relative);
|
||||
var extension = path.extname(file);
|
||||
var filename = path.basename(file, extension); // filename without extension
|
||||
var title = filename.charAt(0).toUpperCase() + filename.substring(1).replace(/_/g, ' ');
|
||||
|
||||
var page = template({
|
||||
title: title,
|
||||
filename: filename + extension,
|
||||
path: 'raw/' + relative,
|
||||
type: extension.substring(1),
|
||||
code: fs.readFileSync(file)
|
||||
});
|
||||
fs.writeFileSync(EXAMPLES_DEST + '/' + (prefix != '.' ? prefix + '_' : '') + filename + '.md', page);
|
||||
|
||||
return {
|
||||
title: title,
|
||||
page: (prefix != '.' ? prefix + '_' : '') + filename + '.html'
|
||||
};
|
||||
});
|
||||
|
||||
callback(results);
|
||||
})
|
||||
}
|
||||
|
||||
generate('*.js', function (files) {
|
||||
generate('browser/*.html', function (browserFiles) {
|
||||
// create an index page
|
||||
var template = handlebars.compile(INDEX_TEMPLATE);
|
||||
var page = template({
|
||||
files: files,
|
||||
browserFiles: browserFiles
|
||||
});
|
||||
fs.writeFileSync(EXAMPLES_DEST + '/index.md', page);
|
||||
|
||||
cb();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Copy and preprocess the history file
|
||||
*/
|
||||
@ -159,4 +250,4 @@ gulp.task('version', ['update'], function (cb) {
|
||||
|
||||
});
|
||||
|
||||
gulp.task('default', ['update', 'lib', 'docs', 'history', 'version']);
|
||||
gulp.task('default', ['update', 'lib', 'docs', 'examples', 'history', 'version']);
|
||||
|
||||
@ -16,6 +16,15 @@ layout: default
|
||||
|
||||
// just do:
|
||||
var math = require('mathjs');
|
||||
- Implemented support for implicit multiplication, like `math.eval('2a', {a:3})`
|
||||
and `math.eval('(2+3)(1-3)')`. This changes behavior of matrix indexes as
|
||||
well: an expression like `[...][...]` is not evaluated as taking a subset of
|
||||
the first matrix, but as an implicit multiplication of two matrices.
|
||||
- Removed utility function `ifElse`. This function is redundant now the
|
||||
expression parser has a conditional operator `a ? b : c`.
|
||||
- Fixed a bug with multiplying a number with a temperature,
|
||||
like `math.eval('10 * celsius')`.
|
||||
- Fixed a bug with symbols having value `undefined` not being evaluated.
|
||||
|
||||
|
||||
## 2014-06-20, version 0.24.1
|
||||
|
||||
1680
js/lib/math.js
1680
js/lib/math.js
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
16
js/lib/math.min.js
vendored
16
js/lib/math.min.js
vendored
File diff suppressed because one or more lines are too long
@ -5,9 +5,12 @@
|
||||
"mathjs": "latest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"glob": "^4.0.3",
|
||||
"gulp": "^3.8.1",
|
||||
"gulp-header": "^1.0.2",
|
||||
"gulp-rename": "^1.2.0",
|
||||
"gulp-util": "^2.2.17"
|
||||
"gulp-util": "^2.2.17",
|
||||
"handlebars": "^2.0.0-alpha.4",
|
||||
"rimraf": "^2.2.8"
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user