Search code examples
clojureroundingapproximationsquare-root

Square root approximation Clojure


I am getting an error and do not know how to fix it. I have to calculate square root with approximation and it should stop on the 20th element.

  • Unable to resolve symbol: aprox in this context, compiling:(/home/jdoodle.clj:2:2)

Code:

(defn msqrt [n]
    (aprox  (n 1.0 1)))
(defn aprox [n prox part]
(if (= part 20)
    prox
(+ (/ n (* 2 (aprox n part (+ part 1)))) (/ (aprox n prox (+ part 1))2)))
)
(msqrt 9)

Solution

  • In Clojure, the order you declare functions in matters. They don't get hoisted up like in Javascript. You can fix this by either:

    1. Moving your defn aprox above defn msqrt
    2. Adding declare aprox to the top of your file to make it available

    https://clojuredocs.org/clojure.core/declare