On Aug 22, 5:56 am, jng27 <jgran...@gmail.com> wrote:
> Took a shot at implementing PI in Clojure using a reasonably fast
> algorithm.
> So why is it so slow ? Is BigDecimal just that bad ? Would fixed point
> arithmetic be better using BigInteger ?
Hmm, my impression is that the java boxed numbers aren't particularly
high-performance, but they shouldn't be slow either. But you're using
too much java in your code...
Why are you using the add method directly? + should work just fine.
Also, I personally do not like . at all. :)
You can set the math context by binding *math-context* to a math
context you need with (binding ...)
Also, nested defns are pointless and REALLY confusing. Do not use
them.
If you need local functions, use letfn or plain (let [foo (fn ...)])
I tried to clean up the thing a bit; it won't work as is because I'm
lazy. I don't set the math context, and it's missing the actual sb-pi
definition because I got confused by your lets. However, if you can
make this version work, it'll be a lot easier to figure out the
slowness.
Note that you don't need to create the bigDec constants yourself; just
use 1M, 2M etc.
(defn big-sqrt-int
[#^BigDecimal num
#^BigDecimal x0
#^BigDecimal x1
digits]
(if-not (== x0 x1)
(recur num
x1
(/ (+ x1 (/ num x1))
2M)
digits)
x1))
(defn big-sqrt[#^BigDecimal num digits]
"Calculates square root using Newton's method."
(big-sqrt-int
num 0M (BigDecimal/valueOf
(Math/sqrt (.doubleValue num)))
(inc digits)))
(defn sb-pi-int
[#^BigDecimal a #^BigDecimal b #^BigDecimal x #^BigDecimal p
n]
(let
[#^BigDecimal a1 (/ (+ a b) 2M)
#^BigDecimal b1 (big-sqrt (* a b) digits)
#^BigDecimal x1 (- x
(* p
(* (- a a1)
(- a a1))))
#^BigDecimal p1 (* 2M p)]
(if (> n digits)
(/ (* (+ a1 b1) (+ a1 b1))
(* 4M x1))
(recur a1 b1 x1 p1 (* 2 n)))))
--
Jarkko
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---