首页 > 解决方案 > Clojure 二次公式

问题描述

(ns quadratic_roots) ;name the program 


(defn quadraticRoots[a b c]
    (/ (+ (- 0 b) (Math/sqrt (- (Math/expt b 2) (* 4 a c)))) (* 2 a)) (/ (- (- 0 b) (Math/sqrt (- (Math/expt b 2) (* 4 a c)))) (* 2 a)))
)

这只是我正在编写的二次公式程序的第一部分。我在试图弄清楚如何使指数方法起作用时遇到了麻烦。另外,我在尝试创建主驱动程序来实现函数 quadraticRoots 时遇到了一些麻烦

标签: clojureformulaquadratic

解决方案


您需要(Math/pow b 2)或只(* b b)需要获得 b^2:

(defn quadraticRoots [a b c]
  ; for simple squares, often simplify (Math/pow b 2) => (* b b)
  (let [discriminant (Math/sqrt (- (Math/pow b 2)
                                 (* 4 a c)))
        root-1       (/ (+ (- b) discriminant)
                       (* 2 a))
        root-2       (/ (- (- b) discriminant)
                       (* 2 a))]
    [root-1 root-2]))

结果(见示例问题):

  ; Example:  x^2 + 4x - 21 = 0
  (let [a 1
        b 4
        c -21]

接着

(quadraticRoots a b c) => [3.0 -7.0]

您可能还希望git clone此模板项目上使用,以便您有一个工作设置来帮助您前进。


更新

数学公式(即使是简单的)通常在计算机代码中无法识别。上述的另一种表述可能如下所示:

(defn quadratic-roots 
  "Solve for the 2 roots of a quadratic equation of the form:

       ax^2 + bx + c = 0 
  "
  [a b c]
  (let [discriminant (Math/sqrt (- (* b b) (* 4 a c)))
        neg-b        (- b)
        inv-a2       (/ 1 (* 2 a))
        root-1       (* inv-a2 (+ neg-b discriminant))
        root-2       (* inv-a2 (- neg-b discriminant))]
    [root-1 root-2]))

推荐阅读