May 15, 2019
The Quadratic Formula
If you have a general quadratic equation like this:
Then the quadratic formula will help you find the roots of a quadratic equation, i.e. the values of x where this equation is solved.
Simplify square roots
Factor and remove perfect squares:
(defn prime-factors
([n] (prime-factors 2 n))
([f n]
(if (> n 1)
(if (zero? (mod n f))
(cons f (prime-factors f (/ n f)))
(recur (inc f) n)))))
(defn perfect-squares [s]
(loop [items (sort s) pairs []]
(if (empty? items) pairs
(if (= (first items) (second items))
(recur (drop 2 items) (conj pairs (first items)))
(recur (rest items) pairs)))))
(defn simplify-sqrt [sqrt]
(let [sq (reduce * (perfect-squares (prime-factors sqrt)))]
[sq (/ sqrt (* sq sq))]))
(defn quadratic-rational [[a b c]]
(let [discriminant (simplify-sqrt (- (* b b) (* 4 a c)))]
[(/ (- b) (first discriminant))
(last discriminant) (/ (* 2 a) (first discriminant))]))
(quadratic-rational [3 24 48])
Graphing quadratic equations
Find the vertex and y-intercept
The x-coordinate of the vertex of a parabola in the form ax2 + bx + c is -b/2a. The y coordinate can then be found by plugging the resulting value into the equation. The y-intercept is (0, c).
(defn graph [[a b c]]
(let [vert-x (/ (- b) (* 2 a))
vert-y (+ (* a (* vert-x vert-x))
(* b vert-x)
c)
y-int [0 c]]
{:vertex [vert-x vert-y]
:y-int y-int}))
(graph [-1 14 0])
Now we have a vector [1 2 3]
containing the values of a simplified rational expression in the form (1 +- sqrt2) over 3.
(defn quadratic-roots [[a b c]]
(let [square (Math/sqrt (- (* b b) (* 4 a c)))]
(str "x = {"
(/ (+ (- b) square) (* 2 a))
", "
(/ (- (- b) square) (* 2 a)) "}")))
[(quadratic-roots [-7 2 9]) (/ 9 7.0)]