Posts

Complex numbers in clojure

avatar of @chasmic-cosm
25
@chasmic-cosm
·
0 views
·
2 min read

As part of an effort to learn the Clojure language, I've set about implementing a basic set of functions for working with complex numbers. There is undoubtedly a better implementation already accessible in Clojure, but implementing this from first principles was great fun and practice.

Clojure is a Lisp implemented on the Java JVM. This is a functional language, and the syntax can be a bit tricky at first. The functional paradigm offers new ways of looking at code, potentially leading to new insights in program construction.

In order to work with complex numbers, the first thing to do is to define a complex number type; A complex number consists of a real part and an imaginary part:

; Define the basic type 
(deftype complex 
  [^double real ^double imag]) 

The next part is to implement a utility function that can output our complex numbers is a user-friendly, readable way. Though not strictly necessary for performing algebra, I found this to be useful:

; Print the complex number in a reasonable way 
(defn print-complex 
  [^complex z] 
  (str (.real z) " + " (.imag z) "i")) 

We can check that we get the output expected by calling the function

(print-complex (complex. 1.0 2.5)) 

gives the output "1.0 + 2.5i".

Next, to implement addition:

; Define the addition operator 
; Since arity is used to determine overloads of functions, 
; we will call this function "plus" instead of "+" 
 
(defn plus 
  [^complex z1 ^complex z2] 
  (complex.  
   (+ (.real z1) (.real z2)) 
   (+ (.imag z1) (.imag z2)))) 

And finally, multiplication:

; Define vector multiplication 
 
(defn mult 
  [^complex z1 ^complex z2] 
  (complex. 
   (+ (<em> (.real z1) (.real z2)) (</em> (.imag z1) (.imag z2))) 
   (+ (<em> (.real z1) (.imag z2)) (</em> (.real z2) (.imag z1))))) 

The construction for multiplication is based on the derivation:

(a + bi) * (c + di) = (ac - bd + (ad + bc)i)


Posted via [proofofbrain.io](https://www.proofofbrain.io/@chasmic-cosm/complex-numbers-in-clojure)