UNPKG

2.03 kBJavaScriptView Raw
1// complex numbers
2
3// load math.js (using node.js)
4const math = require('../index')
5
6// create a complex number with a numeric real and complex part
7console.log('create and manipulate complex numbers')
8const 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
16const 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
24const 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
37console.log()
38
39// create a complex number from polar coordinates
40console.log('create complex numbers with polar coordinates')
41const c = math.complex({ r: math.sqrt(2), phi: math.pi / 4 })
42print(c) // 1 + i
43
44// get polar coordinates of a complex number
45const d = math.complex(3, 4)
46console.log(d.abs(), d.arg()) // radius = 5, phi = 0.9272952180016122
47console.log()
48
49// comparision operations
50// note that there is no mathematical ordering defined for complex numbers
51// we can only check equality. To sort a list with complex numbers,
52// the natural sorting can be used
53console.log('\ncomparision and sorting operations')
54console.log('equal', math.equal(a, b)) // returns false
55const values = [a, b, c]
56console.log('values:', math.format(values, 14)) // [5 + 3i, 3 - 7i, 1 + i]
57math.sort(values, 'natural')
58console.log('sorted:', math.format(values, 14)) // [1 + i, 3 - 7i, 5 + 3i]
59
60/**
61 * Helper function to output a value in the console. Value will be formatted.
62 * @param {*} value
63 */
64function print (value) {
65 const precision = 14
66 console.log(math.format(value, precision))
67}