zcaudate
zcaudate

Reputation: 14258

finding all the power roots in clojure

This is a rehash of Finding integer power roots but in clojure:

How do i find ALL the integer roots of a number?

So I want a function:

(defn roots [ex num] .....)

that when called gives:

(roots 4 81) => [3, -3, 3i, -3i]

Upvotes: 1

Views: 533

Answers (2)

zcaudate
zcaudate

Reputation: 14258

The best library I found for Maths is the apache commons math library

to use add this to your project.clj

[org.apache.commons/commons-math3 "3.0"]

it comes with an nth-root method built in and the following can be wrappers:

(import org.apache.commons.math3.complex.Complex)

(defn complex
  ([re] (complex re 0))
  ([re im]
      (Complex/valueOf re im)))

(defn nth-root [#^Complex c m] (seq (.nthRoot c m)))

(defmethod print-method
  Complex
  [this w]
  (print (format "(%f %fi)" (re this) (im this))))

(nth-root (complex 1 4) 6)
;; => ((1.235513 0.277543i) (0.377397 1.208757i) (-0.858115 0.931214i) (-1.235513 -0.277543i) (-0.377397 -1.208757i) (0.858115 -0.931214i))

Upvotes: 2

tnoda
tnoda

Reputation: 1524

user> (defn nth-root
          [n x]
        (long (Math/pow x (/ 1.0 n))))
#'user/nth-root
user> (nth-root 4 81)
3

To be honest, I do not know the standardized way to handle a complex number in Clojure. You might have to implement your own Complex record, using defrecord.

Upvotes: 1

Related Questions