clojure精密计数器

时间:2015-08-03 16:38:45

标签: clojure double decimal precision

如何确定小数点后的位数。

[ 1.6712 2.053 3.52 ]
;;1.6712 => 4
;;2.053 => 3
;;3.52 => 2

2 个答案:

答案 0 :(得分:1)

请记住: What Every Computer Scientist Should Know About Floating-Point Arithmetic

这可能是一个微不足道的/数学尝试。

但是这对每一个双倍都不起作用!

(defn more-than-5 [number]
   (let [n (* number 10E4)]
     (pos? (- n (int n)))))

这种方法应该有效:

(defn primefactors
  ([n]
   (primefactors n 2 '()))
  ([n candidate acc]
   (cond (<= n 1) (reverse acc)
     (zero? (rem n candidate)) (recur (/ n candidate) candidate (cons candidate acc))
     :else (recur n (inc candidate) acc))))

来自https://stackoverflow.com/a/9556744

的primefactors函数
(defn length-of-period [n]
  (if (integer? n)
      [0 0]
      (let [groups (->> n
                        rationalize
                        denominator
                        primefactors
                        (group-by #(zero? (mod 10 %))))
            b1 (apply * (get groups true))
            b2 (apply * (get groups false))]
       [(count (take-while
                  #(pos? (mod % b1))
                  (take 20 (iterate #(bigint (* 10 %)) 1))))
        (count (take-while
                  #(pos? (mod % b2))
                  (take 20 (iterate #(bigint (- (* 10 %) 1)) 1))))])))

结果是向量[length-of-preperiod length-of-period] 示例:

(length-of-period 0.123456) => [6 0]
(length-of-period 1/3) => [0 1]
;; 1/3 = 0.3333...
(length-of-period 7/12) => [2 1]
;; 7/12 = 0.583333....

因此,如果是双打,您可以使用#(> 6 (first (length-of-period %)))

过滤您的号码

答案 1 :(得分:0)

来自:Number of decimal digits in a double

  

双精灵并不总是精确的表现形式。您只能说明如果将其转换为字符串,您将获得多少小数位。