Floating point precision #1158
-
Hi everyone 👋 Sorry, I pretty new to Janet and have been enjoying using it so far, but I came across an issue: I'm playing around with Janet and want to calculate Pi via the Leibniz formular. (defn calc-pi-leibniz
"Translation of Java/Clojure solution to Janet"
[rounds]
(var pi 1.0)
(var x 1.0)
(loop [i :range [2 (+ 2 rounds)]]
(*= x -1)
(+= pi (/ x (dec (* 2 i)))))
(* 4 pi))
(def rounds 100000000)
(print (string (calc-pi-leibniz rounds))) Output: If I run similar Clojure code, I get much higher precision: (ns leibniz)
(set! *unchecked-math* :warn-on-boxed)
(defn calc-pi-leibniz
"Translation of Java solution to Clojure"
[^long rounds]
(let [end (+ 2 rounds)]
(loop [i 2 x 1.0 pi 1.0]
(if (= i end)
(* 4 pi)
(let [x (- x)]
(recur (inc i) x (+ pi (/ x (dec (* 2 i))))))))))
(defn parse-int [s]
(Integer/parseInt (re-find #"\A-?\d+" s)))
(def rounds 100000000)
(println (calc-pi-leibniz rounds)) Would it be possible to get higher precision, similar to Clojure with Janet? If yes, how can I do that? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The lack of precision is only in the default representation of floating point numbers. Try this:
|
Beta Was this translation helpful? Give feedback.
The lack of precision is only in the default representation of floating point numbers. Try this: