Bobbi Towers / May 10 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 where this equation is solved.

1. 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))]))
user/simplify-sqrt
(defn quadratic-rational [[a b c]]
  (let [discriminant (simplify-sqrt (- (Math/abs (* b b)) (* 4 a c)))]
    [(/ (- b) (first discriminant))
     (last discriminant) (/ (* 2 a) (first discriminant))]))

(quadratic-rational [3 24 48])
Vector(3) [-24, 0, 6]

2. Graphing quadratic equations

2.1. Find the vertex and y-intercept

The -coordinate of the vertex of a parabola in the form is . The coordinate can then be found by plugging the resulting value into the equation. The -intercept is .

(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 -6 -3])
Map {:vertex: Vector(2), :y-int: Vector(2)}

Now we have a vector [1 2 3] containing the values of a simplified rational expression in the form .

(defn quadratic-roots [[a b c]]
  (let [square (Math/sqrt (- (Math/abs (* b b)) (* 4 a c)))]
  (str "x = {"
       (/ (+ (- b) square) (* 2 a))
       ", "
       (/ (- (- b) square) (* 2 a)) "}")))

[(quadratic-roots [-7 2 9]) (/ 9 7.0)]
Vector(2) ["x = {-1.0, 1.2857142857142858}", 1.2857142857142858]