simple-squiggle

A restricted subset of Squiggle
Log | Files | Refs | README

complex_numbers.js (2001B)


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