Generating PI in Clojure 57

Posted by Uncle Bob Wed, 05 Aug 2009 13:07:00 GMT

The SICP book shows a cute algorithm for computing PI using infinite sequences (lazy evaluation). I have adapted it for Clojure and modified it to use Java’s BigDecimal class, so that I can generate arbitrary precision.

First we define a function that generates an “infinite” list of terms of the form 1/1 + 1/3 – 1/5 + 1/7 – ... This is a well known series that very slowly converges on Pi. Notice that I’m using the ‘M’ suffix to denote BigDecimal, and I’m restricting the precision to 300 places. Notice also that I’m using lazy-seq. This function delays the execution of the ‘cons’ term until that part of the list is actually used. This allows the list to appear to be infinite.

(defn pi-summands [n]
  (lazy-seq
    (cons (with-precision 300 (/ 1M n))
      (map - (pi-summands (+ n 2))))))

Next we have two utility functions. The first multiplies the terms of a list by a scale factor. The other adds two lists together producing a list of sums. If the input lists are ‘infinite’, the output lists will also be ‘infinite’.

(defn scale-stream [stream factor]
  (map (fn [x] (* x factor)) stream))

(defn add-streams [p q]
  (map +  p q))

partial-sums takes a list of terms produces a list of the sums of those terms. Given [a b c] it produces [a a+b a+b+c]. And, again, the lists can be infinite.

(defn partial-sums [s]
  (lazy-seq
    (cons (first s) (add-streams (next s) (partial-sums s)))))

pi-stream mutiplies the partial-sums of the pi-summands by 4. Turning the summing sequence into 4/1 + 4/3 – 4/5…

(def pi-stream
  (scale-stream (partial-sums (pi-summands 1)) 4))

A simple squaring function.

(defn square [s] (* s s))

Euler’s transform is a fancy way to average three terms of a +/- sequence. It can dramatically increase the precision of an otherwise slowly converging sequence. The euler-transform function produces a sequence of results from the pi-stream. Again, note the constraint I place on BigDecimal precision.

(defn euler-transform [s]
  (let [s0 (nth s 0)
        s1 (nth s 1)
        s2 (nth s 2)]
    (lazy-seq
      (cons (with-precision 300 (- s2 (/ (square (- s2 s1))
        (+ s0 (* -2 s1) s2))))
        (euler-transform (next s))))))

It turns out that you can use Euler’s transform on it’s own results to further increase precision. The make-tableau function arranges the reapplication of a transform so that it can be repeatedly applied to itself.

(defn make-tableau [transform s]
  (lazy-seq
    (cons s (make-tableau transform (transform s)))))
And now we grab the first element of each repetition.
(defn accelerated-sequence [transform s]
  (map first (make-tableau transform s)))

A little utility to print the elements of a list.

(defn print-list [s] (doseq [n s] (println n)))
And now finally we print the first 150 iterations of the accelerated euler-transformation of the pi sequence.
(print-list (take 150
  (accelerated-sequence euler-transform pi-stream)))

The 150th result (the first two lines of which are accurate) 3.14159265358979323846264338327950288419716939 93751058209749445923078164062862089986280348253 25256352154500957038098311477352066337027814620 46050836612955894790973622135628850706785335611 34661971615744147647325427374216175843967838084 09640502874355811103562027043480098593797655792 36344321165429010895M

Comments

Leave a response

  1. Avatar
    Michael Feathers 31 minutes later:

    I love laziness. A while back, I wrote a Mandelbrot Set generator in Haskell. The computation I formed was over an infinite grid ([0..] in x and y). Afterward, I used this function to “pluck” out interesting areas. With laziness, these areas were computed on demand:

    
    window :: (Int, Int) -> (Int, Int) -> [[a]] -> [[a]]
    window (x0, x1) (y0, y1) = range y0 y1 . map (range x0 x1) where
      range m n = take n . drop m
    

    This is a form of abstraction which is harder to achieve in non-lazy languages. You form a general computation and impose the edges later.

  2. Avatar
    Tyler Jennings about 8 hours later:

    You inspired me to try this in Scala. I had some trouble reading the prefix notation, but I think I figured it out. My result for the 150th value in the sequence is close to yours, but not identical. May have to do with the type of rounding I’m doing on the division.

    Doesn’t feel as nice as your clojure version, but I’m a Scala newbie. There is probably a much better way.

    http://gist.github.com/162977

  3. Avatar
    Jeff about 22 hours later:

    Instead of using lazy-seq “manually” you could use some of the build in Clojure functions. For example, you can write pi-summands using the standard iterate function (in a slightly evil feeling way and I’m sure there’s a better way to do this!)

    (def pi-summands (map first (iterate (fn [[x y]] (let [n (+ y 2)] [(/ 1 n) n])) [1 1])))

    Clojure also has some nifty short-hand syntax

    (defn scale-stream [stream factor] (map #(* % factor) stream))

    Where # indicates an anonymous function of one argument (represented by %).

  4. Avatar
    Tyler Jennings 1 day later:

    I thought I’d attempt a clone of your algorithm in Scala, since I’m learning that. Here’s my best result so far:

    http://gist.github.com/162860

    Still some rough edges in 2.7.5 I felt compelled to work around (BigDecimal support, no cons(::) operator for streams. The Clojure version feels cleaner to me – even though I’m not comfortable with prefix notation.

    All the type definitions are required, of course. However, I feel like they’re more clutter than useful to the developer.

  5. Avatar
    piyo 1 day later:

    Great stuff. I learned something new.

    @Jeff:You missed the part where the summands are negative on every other term. Uncle Bob’s explicit lazy-seq is really novel with the “map -”!

    @Uncle Bob: You can use the deconstructing bind (“Vector binding-exprs”) for your euler-transform instead of let:

    (defn euler-transform [[s0 s1 s2 :as s]] ...)

    Also I find I get a “Divide by zero error” and/or “Stack overflow error” if I try to calculate a lot of terms, like say 350, with your implementation. i.e.

    (print-list (take 50 (drop 300 pi-terms)))

    -> ... java.lang.ArithmeticException: Divide by zero

    BTW, 300 terms yields 126 correct digits, while my implementation of the Calculating Pi using the van Wijngaarden transformation yields 296 digits after 300 terms, which comes closer to the limits set by the with-precision. (Actually the comparison is more like apples to oranges, because the latter is calculating more. Oh well.) Still, 126 digits ought to be enough for anybody (in this universe).

  6. Avatar
    Heikki 1 day later:

    The Leibniz series actually converges on Pi/4, but the second paragraph says it converges on Pi. It took me a while to understand what the multiplication was needed for.

    However, it’s very nice to read and try to grasp lisp after 8 or so years from taking the SICP course.

  7. Avatar
    Kooba Handbags 8 months later:

    Living without an aim is like sailing without a compass. with a new http://www.handbags4buy.com/ idea is a crank until the idea succeeds.

  8. Avatar
    moncler clearance 8 months later:

    Very quietly I take my leave.To seek a dream in http://www.edhardy-buy.com/ starlight.

  9. Avatar
    han 8 months later:

    mutiplies the partial-sums of the pi-summands by 4. Turning the summing sequence into 4/1 + 4/3 – 4/5…

  10. Avatar
    hair accessories about 1 year later:

    The SICP book is very well.

  11. Avatar
    bag manufacturer about 1 year later:

    denote BigDecimal, and I’m restricting the precision to 300 places. Notice also

  12. Avatar
    electric radiators about 1 year later:

    An electric radiator can offer an energy efficient heating solution to your home.Make your home become warm in a short time with the high efficiency.T he electric towel rail made the towels warm and softy during your bath time.You can have a comfortable touch of luxury to have a warm towels and wouldn`t worried about is.We supply all types of radiators includingelectric radiators and electric towel rail.The electric towel rails give you the most luxury life in the bath room.The electric towel rails keep the towels dry all the time.

  13. Avatar
    moncler about 1 year later:

    I think I figured it out. My result for the 150th value in the sequence is close to yours, but not identical. May have to do with the type of rounding I’m doing on the division.

  14. Avatar
    canada goose about 1 year later:

    we offer you canada goose to enjoy the winter!! Canada goose jakkesnug Goose jakkeYou’re Worth It Canada goose jakkerremain stylish Canada goose parkais a trustworthy brand Canada goose tilbudis the best one

    canada goosewarm canada goose parka protection canada goose expeditionfashionable canada goose jakkerlet you have Happy winter canada goose jakkeGood quality

    canada goose jacka vogue goose jacka pretty canada goose jackordifferent designs outlet canada goose amazing canada goose Expedition smooth welcome to buy!thank you!

  15. Avatar
    Dog bark collar about 1 year later:

    Multiplies the partial-sums of the pi-summands by 4. Turning the summing sequence into 4/1 + 4/3 – 4/5

  16. Avatar
    moncler about 1 year later:

    This is a great blog, I’ve loved having a look around today. moncler jackets I’m sure you could definitely make a dollar or two if you sold some more advertising on here!moncler

  17. Avatar
    ugg outlet stores about 1 year later:

    Thanks for the compliment. I’ve straddled the state line a few times while enjoying a nice cool beverage at the FloraBama. It’s on my list of faves.ugg online outlet

  18. Avatar
    Pandora about 1 year later:

    it probably doesn’t deserve all of the build up that I just gave it, but I suspect that I’ll be writing more about this topic. There’s definitely more to discuss.

  19. Avatar
    Silicone Molding about 1 year later:

    Mold making is the core business of Intertech (Taiwan). With world level technology, Intertech enjoys a very good reputation for making Injection Mold and Plastic Moldsfor their worldwide customers.

  20. Avatar
    moncler about 1 year later:

    thanks for Moncler Jackets || Christian louboutin UK || Moncler coats || Christian louboutin shoes || Christian louboutin pumps your post!

  21. Avatar
    garbage bag making machine about 1 year later:

    This is one of the most professional manufacturers and suppliers in plastic packing machinery. We mainly provide non woven bag making machine,disposable glove machines,blowing film machines,flexo printing machines,garbage bag making machine etc.

  22. Avatar
    Criminal Records about 1 year later:

    The euler-transform function produces a sequence of results from the pi-stream. Again, note the constraint I place on BigDecimal precision.

  23. Avatar
    cars in pictures about 1 year later:

    good May have to do with the type of rounding I’m doing on the division.

  24. Avatar
    dswehfhh about 1 year later:

    We are the professional shorts manufacturer, shorts supplier, shorts factory, custom shorts.

  25. Avatar
    Real Quick review about 1 year later:

    I wonder if u can do this in other Programming languages?

  26. Avatar
    wholesale hair extensions about 1 year later:

    Skin Prep Pads (I use Cavilon) Migthy Tite Glue *(not necessary …your choice) EnduraBond (from Truetape)

  27. Avatar
    wholesale hair weave about 1 year later:

    25% IC MOisturiser (make sure its the one in the brown bottle w/ the Aloe Vera plant on it) Fast track knot sealer (from Adventhair) Fray Block (at Walmart, Fabric stores)

  28. Avatar
    enev about 1 year later:

    I am rather glad to see such information which I was searching for a long time.

  29. Avatar
    tiffany and co outlet about 1 year later:

    A bad beginning makes a bad ending. A bird in the hand is worth than two in the bush. A year’s plan starts with

    spring. Bad news has wings. Better to ask the way than go astray. By reading we enrich the mind, by conversation we

    polish it. Custom makes all things easy. He is not fit to command others that cannot command himself. He laughs best

    who laughs last. tiffany and co outlet

  30. Avatar
    okey oyunu oyna about 1 year later:

    i need it. Thanks

    internette görüntülü olarak okey oyunu oyna, gerçek kisilerle tanis, turnuva heyecanini yasa.

  31. Avatar
    coach purses about 1 year later:

    Mr Coates coach purses is the longest U.S. market popular with one of the most successful leather brand. Mr Coates coach purses store represents the most admirable American fashion innovative style and traditional skills . Mr Coates coach bags have durable quality and exquisite technology, Conspicuous Coach Heels in the female consumers have good reputation. Welcome to our shop Elegant Coach Purses

  32. Avatar
    customized running shirts about 1 year later:

    I miss this old code practice.

  33. Avatar
    beats by dr dre headphones about 1 year later:

    I attempted these beats by dr dre studio out in several genres thinking about which i listen to an eclectic mix Beats By Dr Dre. a washing cloth as well as the manual. Do not purchase any beats by dr dre solo purple products inside the internet unless you’re getting from an Authorized internet DealerBeats By Dre Just Solo. We are reliable provide good beats by dr dre pro black by reduced price.

  34. Avatar
    cheap ray ban sunglasses about 1 year later:

    Weekend ago, I purchased this ray ban online here. Today, I come here to select another cheap ray ban sunglasses for my son. I am fond of good sunglasses for the charm I bought here.

  35. Avatar
    provillus about 1 year later:

    Blog posts about wedding and bridal are always rare to find , at least with great quality,you qualify for a great blog post writer title,kep the great job happening

  36. Avatar
    Pickourstyle about 1 year later:

    Thank you so much for the English translation! I love this shawl and will be making is soon.

  37. Avatar
    takewatch about 1 year later:

    This shawl just jumped to the top of my project list! Very pretty indeed. Thanks for sharing the pattern with us.

  38. Avatar
    toppuma about 1 year later:

    very interesting article,and i am so happy to see this,thanks to lovely share

  39. Avatar
    Woodor over 2 years later:

    Never would have thunk I would find this so indisepsnable. | Backpack

  40. Avatar
    beats by dre store over 2 years later:

    y project list! Very pretty indeed. Thanks for sharing the pattern with ubeats by dre sale cheap beats by dre

  41. Avatar
    Pronovias over 2 years later:

    Excellent article?The Jovani dress showed in the picture are very beautiful. Can you tell me where I can buy a mori lee dress at a low price

  42. Avatar
    cheap Ash running sneakers over 2 years later:

    Wow I read about it, but to be honest I never watched any picture of it, Ash sandals Ash womens sandals cheap Ash thong sandals Ash reef sandals it was truly a serious event, the climate its changing very rapidly around the world, maybe the 2012 premonition is true.

  43. Avatar
    ed hardy cheap over 2 years later:

    Great post. Please write more and more about this.

  44. Avatar
    Cheap Christian Louboutins over 2 years later:

    Great post. Please write more and more about this.

  45. Avatar
    bagsupplyer over 2 years later:

    I really enjoy your articles. Very well written. wholesale women replicate Coach backpacks more order,more discount

  46. Avatar
    http://bandage-dresses.net/ over 2 years later:

    Bandage Dresseswill show your beautiful line and tender silhouette. Each clipping of Bandage Dresses is close to the body, and by this way can make you more comfortable and sexy. If you want yourself posses perfect figure, if you imagine yourself the focus in any occasions, the Bandage Dresseswill be your best choice. Note:Dry clean only. Rayon, Nylon, Spandex.

  47. Avatar
    MTS ????????? over 2 years later:

    The public may not have known what the messages meant, but it helped pay for them. The skywriting stunt was supported by city and state public funding, according to the High Line’s website. MTS ??? “I wanted a narrative trajectory towards something optimistic at the end, which was the last message, ‘Now Open,’” she said of the work. MTS ??? Mac

  48. Avatar
    canada goose coat over 2 years later:

    When it comes to feather dress, what appears in your mind? Which kind brand of down jacket do you like prefer? Though there are many down jackets for you to choose from, on the word, which one you really enjoy? I want to say that canada goose coats is really your best choice. I believe you can’t agree with me any more. When you take the quality into consideration, you will find that it is superior to any other kind of coat. Besides, discount canada goose jackets is a world well-known brand, which has gained high reputation in the world, which has accepted by our customers and some organization. Because of its high quality, some of our loyal customers have promoted it to the people around them. In their opinion, it is good to informing others to know it. Recently, Canada Goose Trillium Parka is on hot sale. What I have to inform you is that all the products there are made by hand, so they are elaborative and elegant enough. It is really beautiful once you dress in. So, if you are a lovely girl or woman, go to the store to buy one for you. You will appreciate it that you have such a coat.In addition, they also have any other products like canada goose Gloves and canada goose jacket supplier.Hope your will like its!

  49. Avatar
    kkkz198608 over 2 years later:

    Afterwards, custom NFL jersey Dorsett said to succeed, the NFL must keep New York Giants teaching the game to as many Chinese kids as possible.Chinese love World Cup Soccer NFL jersey custom and NBA basketball. Selling them NFL New England Patriots football has proven much more difficult. On Sunday, the NFL set Philadelphia Eagles up an elaborate, interactive exhibition NFL custom jerseys outside a Shanghai stadium in an attempt to build a fan custom NFL jerseys base in the world’s most populous nation.

  50. Avatar
    http://www.northfacejacketsaleclearance.org/north-face-gore-tex-c-15.html over 2 years later:

    For non-monarch said: I plan for her for years until now affair nod to blow assured. Afterwards she confused to Kyoto, we would not acquire appear

  51. Avatar
    the north face gore tex over 2 years later:

    here, aggregate today here, feel chargeless to allocution about my memories! And June road: monks of the bodies I consistently brash afflicted to

  52. Avatar
    gianmarco lorenzi over 2 years later:

    into soil, too slick

  53. Avatar
    outlet juicy couture over 2 years later:

    Shopping inside a incredibly outlet juicy couture sale in regards to the web can be incredibly a great offer handy especially once the regional shop outlet exactly where it is possible to buy the item that you desire is a good offer out of your area. Apart from this, going to malls demands some trip and of course, you would ought to devote resources to the fare of going to mall.

  54. Avatar
    Discount Louboutin Shoes over 2 years later:

    Every women always has Christian Louboutins Wedding Shoes turn of fame but it also has its own goodbyes.

  55. Avatar
    website design bangalore over 3 years later:

    I really enjoyed this site. This is such a Great resource that you are providing and you give it away for free. It gives in depth information. Thanks for this valuable information. http://www.nuvodev.com/

  56. Avatar
    bladeless fans over 3 years later:

    Generating PI in Clojure 55 good post35

  57. Avatar
    louboutin sales over 3 years later:

    Generating PI in Clojure 56 hoo,good article!!I like the post!158

Comments