1 | // complex numbers
|
2 |
|
3 | // load math.js (using node.js)
|
4 | var math = require('../index');
|
5 |
|
6 | // create a complex number with a numeric real and complex part
|
7 | console.log('create and manipulate complex numbers');
|
8 | var a = math.complex(2, 3);
|
9 | print(a); // 2 + 3i
|
10 |
|
11 | // read the real and complex parts of the complex number
|
12 | print(a.re); // 2
|
13 | print(a.im); // 3
|
14 |
|
15 | // clone a complex value
|
16 | var clone = a.clone();
|
17 | print(clone); // 2 + 3i
|
18 |
|
19 | // adjust the complex value
|
20 | a.re = 5;
|
21 | print(a); // 5 + 3i
|
22 |
|
23 | // create a complex number by providing a string with real and complex parts
|
24 | var b = math.complex('3-7i');
|
25 | print(b); // 3 - 7i
|
26 | console.log();
|
27 |
|
28 | // perform operations with complex numbers
|
29 | console.log('perform operations');
|
30 | print(math.add(a, b)); // 8 - 4i
|
31 | print(math.multiply(a, b)); // 36 - 26i
|
32 | print(math.sin(a)); // -9.6541254768548 + 2.8416922956064i
|
33 |
|
34 | // some operations will return a complex number depending on the arguments
|
35 | print(math.sqrt(4)); // 2
|
36 | print(math.sqrt(-4)); // 2i
|
37 |
|
38 | // create a complex number from polar coordinates
|
39 | console.log('create complex numbers with polar coordinates');
|
40 | var c = math.complex({r: math.sqrt(2), phi: math.pi / 4});
|
41 | print(c); // 1 + i
|
42 |
|
43 | // get polar coordinates of a complex number
|
44 | var d = math.complex(3, 4);
|
45 | console.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
|
51 | console.log('\ncomparision and sorting operations');
|
52 | console.log('equal', math.equal(a, b)); // returns false
|
53 | var values = [a, b, c];
|
54 | console.log('values:', math.format(values, 14)); // [5 + 3i, 3 - 7i, 1 + i]
|
55 | math.sort(values, 'natural');
|
56 | console.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 | */
|
62 | function print (value) {
|
63 | var precision = 14;
|
64 | console.log(math.format(value, precision));
|
65 | }
|