Created
October 18, 2024 14:36
-
-
Save slipset/b1cc27f0b7db2d1b7cdbb8f1a8c66e37 to your computer and use it in GitHub Desktop.
Some Leibniz code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; https://github.com/niklas-heer/speed-comparison/tree/master | |
;; Decompilation provided by clj-java-decompiler | |
(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)))))))))) | |
public static Object invokeStatic(final long rounds) { | |
final long end = Numbers.add(2L, rounds); | |
long i = 2L; | |
double x = 1.0; | |
double pi = 1.0; | |
while (i != end) { | |
final double x2 = -x; | |
final long inc = Numbers.inc(i); | |
final double n = x2; | |
pi += Numbers.divide(x2, Numbers.dec(Numbers.multiply(2L, i))); | |
x = n; | |
i = inc; | |
} | |
return Numbers.multiply(4L, pi); | |
} | |
(defn calc-pi-leibniz-2 | |
"Translation of Java solution to Clojure" | |
^double [^long rounds] | |
(let [end (unchecked-add (long 2) rounds)] | |
(loop [i 2 x 1.0 pi 1.0] | |
(if (= i end) | |
(* 4.0 pi) | |
(let [x (- x)] | |
(recur (unchecked-inc i) | |
x | |
(unchecked-add pi | |
(/ x | |
(double (unchecked-dec (unchecked-multiply 2 i))))))))))) | |
public static double invokeStatic(final long rounds) { | |
final long end = 2L + rounds; | |
long i = 2L; | |
double x = 1.0; | |
double pi = 1.0; | |
while (i != end) { | |
final double x2 = -x; | |
final long n = i + 1L; | |
final double n2 = x2; | |
pi += x2 / (2L * i - 1L); | |
x = n2; | |
i = n; | |
} | |
return 4.0 * pi; | |
}f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment