Golang : Calculations using complex numbers example
Alright, you need to calculate the last known position of UFOs and their flying trajectory in Golang or you just want to perform some calculations using complex numbers.
Declaring complex numbers and performing calculations on the numbers is simple in Golang. Pretty much similar to how Python declare complex numbers.
In Python:
>>> a = complex(100,8)
>>> a
(100+8j)
>>> a.real
100.0
>>> a.imag
8.0
In Golang and some examples on how to perform calculations with math/cmplx
package:
package main
import (
"fmt"
"math/cmplx"
)
const a = complex(100, 8)
const b = complex(8, 100)
func main() {
fmt.Println("Complex number a : ", a)
fmt.Println("Complex number b : ", b)
fmt.Println("Get the real part of complex number a : ", real(a))
fmt.Println("Get the imaginary part of complex number b : ", imag(a))
conjugate := cmplx.Conj(a)
fmt.Println("Complex number a's conjugate : ", conjugate)
c := a + b
fmt.Println("a + b complex number : ", c)
fmt.Println("Cosine of complex number b : ", cmplx.Cos(b))
// see https://golang.org/pkg/math/cmplx/
// for more functions such as sine, log, exponential
}
Happy coding!
References:
https://en.wikipedia.org/wiki/Complex_number
https://golang.org/pkg/builtin/#complex
https://golang.org/pkg/math/cmplx/
https://www.socketloop.com/references/golang-builtin-complex-function-example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.7k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+17.9k Golang : Check if a directory exist or not
+18.3k Golang : Aligning strings to right, left and center with fill example
+7.1k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+9.1k Golang : Generate EAN barcode
+6.7k How to let Facebook Login button redirect to a particular URL ?
+8.9k Golang : Handle sub domain with Gin
+9.2k Golang : Play .WAV file from command line
+6.2k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+11.5k Golang : Secure file deletion with wipe example
+10.2k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+5k Golang : Convert lines of string into list for delete and insert operation