Clojure - 如何设置较低的精度
Clojure - How to set the lower precision
我知道要在 Clojure 中设置数字的精度我应该使用 with-precision
函数而且我知道它只适用于 BigDecimal 值。
(defn bar-triang [[a b] [c d] [e f]]
(def cen [(/ (+ a c) 2.0) (/ (+ b d) 2.0)])
(def g (get cen 0))
(def h (get cen 1))
[(with-precision 4 (+ (bigdec g) (/ (- e g) 3M)))
(with-precision 4 (+ (bigdec h) (/ (- f h) 3M)))])
(bar-triang [4, 6], [12, 4], [10, 10])
=> [8.666666666666666 6.666666666666667]
在这里,我将精度设置为 4,但 REPL 给我的数字与以前相同,但位数更多。此外,我使用 bigdec
将 g
和 h
强制为 BigDecimal,但问题仍然存在。我该如何解决这个问题?
稍后进行一些重构:
- 使用
let
代替 def
- 当你只需要
h
和 g
时,为什么要生成 cen
向量
- 对数字文字使用
_M
- 将整个内容包装在
with-precision 4
中
- 放弃
bigdec
强制转换 (thx /u/glts)
- 这可能不是最好的变体,但据我所知它会产生你想要的输出
- 可能是 apply/research 使用 clojure 进行自动化测试的好时机
(defn bar-triang [[a b] [c d] [e f]]
(with-precision 4
(let [g (/ (+ a c) 2M)
h (/ (+ b d) 2M)]
[(+ g (/ (- e g) 3M))
(+ h (/ (- f h) 3M))])))
#'user/bar-triang
user=> (bar-triang [4, 6], [12, 4], [10, 10])
[8.667M 6.667M]
我知道要在 Clojure 中设置数字的精度我应该使用 with-precision
函数而且我知道它只适用于 BigDecimal 值。
(defn bar-triang [[a b] [c d] [e f]]
(def cen [(/ (+ a c) 2.0) (/ (+ b d) 2.0)])
(def g (get cen 0))
(def h (get cen 1))
[(with-precision 4 (+ (bigdec g) (/ (- e g) 3M)))
(with-precision 4 (+ (bigdec h) (/ (- f h) 3M)))])
(bar-triang [4, 6], [12, 4], [10, 10])
=> [8.666666666666666 6.666666666666667]
在这里,我将精度设置为 4,但 REPL 给我的数字与以前相同,但位数更多。此外,我使用 bigdec
将 g
和 h
强制为 BigDecimal,但问题仍然存在。我该如何解决这个问题?
稍后进行一些重构:
- 使用
let
代替def
- 当你只需要
h
和g
时,为什么要生成 - 对数字文字使用
_M
- 将整个内容包装在
with-precision 4
中
- 放弃
bigdec
强制转换 (thx /u/glts) - 这可能不是最好的变体,但据我所知它会产生你想要的输出
- 可能是 apply/research 使用 clojure 进行自动化测试的好时机
cen
向量
(defn bar-triang [[a b] [c d] [e f]]
(with-precision 4
(let [g (/ (+ a c) 2M)
h (/ (+ b d) 2M)]
[(+ g (/ (- e g) 3M))
(+ h (/ (- f h) 3M))])))
#'user/bar-triang
user=> (bar-triang [4, 6], [12, 4], [10, 10])
[8.667M 6.667M]