UNPKG

2.21 kBJavaScriptView Raw
1// complex numbers
2
3// load math.js (using node.js)
4var math = require('../index');
5
6// create a complex number with a numeric real and complex part
7console.log('create and manipulate complex numbers');
8var a = math.complex(2, 3);
9print(a); // 2 + 3i
10
11// read the real and complex parts of the complex number
12print(a.re); // 2
13print(a.im); // 3
14
15// clone a complex value
16var clone = a.clone();
17print(clone); // 2 + 3i
18
19// adjust the complex value
20a.re = 5;
21print(a); // 5 + 3i
22
23// create a complex number by providing a string with real and complex parts
24var b = math.complex('3-7i');
25print(b); // 3 - 7i
26console.log();
27
28// perform operations with complex numbers
29console.log('perform operations');
30print(math.add(a, b)); // 8 - 4i
31print(math.multiply(a, b)); // 36 - 26i
32print(math.sin(a)); // -9.6541254768548 + 2.8416922956064i
33
34// some operations will return a complex number depending on the arguments
35print(math.sqrt(4)); // 2
36print(math.sqrt(-4)); // 2i
37
38// create a complex number from polar coordinates
39console.log('create complex numbers with polar coordinates');
40var c = math.complex({r: math.sqrt(2), phi: math.pi / 4});
41print(c); // 1 + i
42
43// get polar coordinates of a complex number
44var d = math.complex(3, 4);
45console.log(d.abs(), d.arg()); // radius = 5, phi = 0.9272952180016122
46
47// comparision operations
48// note that there is no mathematical ordering defined for complex numbers
49// we can only check equality. To sort a list with complex numbers,
50// the natural sorting can be used
51console.log('\ncomparision and sorting operations');
52console.log('equal', math.equal(a, b)); // returns false
53var values = [a, b, c];
54console.log('values:', math.format(values, 14)); // [5 + 3i, 3 - 7i, 1 + i]
55math.sort(values, 'natural');
56console.log('sorted:', math.format(values, 14)); // [1 + i, 3 - 7i, 5 + 3i]
57
58/**
59 * Helper function to output a value in the console. Value will be formatted.
60 * @param {*} value
61 */
62function print (value) {
63 var precision = 14;
64 console.log(math.format(value, precision));
65}