【问题标题】:Clojure - How to set the lower precisionClojure - 如何设置较低的精度
【发布时间】:2016-03-02 11:07:26
【问题描述】:

我知道要在 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 给了我与以前相同的数字,但数字更多。此外,我使用bigdecgh 强制转换为BigDecimal,但问题仍然存在。我该如何解决这个问题?

【问题讨论】:

  • 不是关于精度,而是声明局部变量使用 let 就像 (let [a 3] ..) - 你实际上将 cen gh 声明为全局可访问变量

标签: clojure precision bigdecimal


【解决方案1】:

稍后进行一些重构:

  1. 使用let 而不是def
  2. 当你只需要hg时为什么要生成cen向量
  3. _M 用于数字文字
  4. with-precision 4包裹整个东西
  5. 删除bigdec 强制(谢谢/u/glts
  6. 这可能不是最好的变体,但据我所知,它会产生您想要的输出
  7. 现在可能是使用 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]

【讨论】:

  • 是的,谢谢,它解决了所描述的问题。但现在我意识到,with-precision 函数计算数字中的所有数字,而我只想限制浮点数之后的数字。
  • @GrigoriyYanushkovsky 所以你想对它进行四舍五入 - 这通常是计算的最后一步(为什么你要使用四舍五入的值进行计算),因此它通常是“字符串”上下文中的操作:见 clojure.core/format - stackoverflow.com/questions/10751638/…
  • @birdspider 不,我只想对结果进行四舍五入。感谢您的帮助!
猜你喜欢
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-22
  • 2018-01-20
  • 1970-01-01
  • 2014-04-02
  • 2021-10-22
相关资源
最近更新 更多