Here's Your Solution
This program finds the solution of the polinominal equation with Newton–Raphson method.
(defn derivative[coeff]
(loop [deg 1
cof (reverse (rest (reverse coeff)))
ans '()]
(if (empty? cof)
ans
(recur (+ deg 1)
(reverse (rest (reverse cof)))
(concat (list (* deg (last cof))) ans)
)
)
)
)
(defn calculate [coeff x]
(loop [deg x
cof (reverse (rest (reverse coeff)))
ans (last coeff)]
(if (empty? cof)
ans
(recur (* deg x)
(reverse (rest (reverse cof)))
(+ (* deg (last cof)) ans)
)
)
)
)
(defn recurr-relation [coeff dev xn]
(- xn (/ (calculate coeff xn) (calculate dev xn)))
)
(defn newtonMeth [coeff start]
(let [dev (derivative coeff)]
(loop [xk start
n 0]
(cond
(= n 100)
(let [err (Math/abs (calculate coeff xk))]
(cond
(< err 1E-6)
xk
(> err 1E+9)
"Error. Change the initial value."
:else
(recur xk 0.0)
)
)
(zero? (calculate coeff xk))
xk
(zero? (calculate dev xk))
"Error. Change the initial value."
:else
(recur (recurr-relation coeff dev xk) (+ n 1))
)
)
)
)
(defn run [] (let [coeff (map #(js/parseFloat %)
(clojure.string/split
(js/prompt "What's the polynomial's coefficient? (2x^2 + x - 3 : 2 1 -3)")
#" "))]
(println (newtonMeth coeff (js/parseFloat (js/prompt "What's the initial value?"))))))