clojure - 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 时遇到了一些麻烦
解决方案
您需要(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]))
推荐阅读
- javascript - 使用控制台代码等待,直到页面上的计时器剩余 10 秒
- json - Neo4j 形成 json 数组
- php - AJAX - 从包含的 AJAX PHP foreach 中删除 MySQL 中的一行
- html - 如何将 ngOptionValue 设置为我的 ng 选项?
- r - 比较两列,如果一列等于 NA,则使用另一列更新它
- reactjs - 如何在 reactjs 中不渲染组件的特定部分
- c# - 无法在 C# 中使用“Microsoft.CrmSdk.XrmTooling.CoreAssembly”连接 Dynamics 365 统一接口
- c# - 单击CustomTaskPane上的按钮时如何更改功能区上的按钮标签(Word Add In VSTO)
- android - 如何将数据从纯原生 android 类传递到 javascript
- flutter - Flutter:每次添加插件时都会出现 Pod 错误