UNPKG

2 kBJavaScriptView Raw
1// complex numbers
2
3// load js (using node.js)
4const { complex, add, multiply, sin, sqrt, pi, equal, sort, format } = require('..')
5
6// create a complex number with a numeric real and complex part
7console.log('create and manipulate complex numbers')
8const a = 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 = complex('3-7i')
25print(b) // 3 - 7i
26console.log()
27
28// perform operations with complex numbers
29console.log('perform operations')
30print(add(a, b)) // 8 - 4i
31print(multiply(a, b)) // 36 - 26i
32print(sin(a)) // -9.6541254768548 + 2.8416922956064i
33
34// some operations will return a complex number depending on the arguments
35print(sqrt(4)) // 2
36print(sqrt(-4)) // 2i
37console.log()
38
39// create a complex number from polar coordinates
40console.log('create complex numbers with polar coordinates')
41const c = complex({ r: sqrt(2), phi: pi / 4 })
42print(c) // 1 + i
43
44// get polar coordinates of a complex number
45const d = 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', equal(a, b)) // returns false
55const values = [a, b, c]
56console.log('values:', format(values, 14)) // [5 + 3i, 3 - 7i, 1 + i]
57sort(values, 'natural')
58console.log('sorted:', 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(format(value, precision))
67}