关于Clojure:Clojure-如何设置较低的精度

Clojure - How to set the lower precision

我知道要在Clojure中设置数字精度,我应该使用with-precision函数,并且我知道它仅适用于BigDecimal值。

1
2
3
4
5
6
7
8
9
(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给我的数字与以前相同,但位数更多。此外,我已经使用bigdecgh强制为BigDecimal,但是问题仍然相同。我该如何解决这个问题?


稍后重构:

  • 使用let而不是def
  • 为什么只需要hg时产生cen向量
  • 使用_M作为数字文字
  • 将整个内容包装在with-precision 4
  • 降低bigdec强制(thx / u / glts)
  • 这可能不是最好的变体,但据我所知,它可以产生所需的输出
  • 现在可能是使用Clojure应用/研究自动化测试的好时机
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    (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]