thanks.  Very subtle difference... definitely not a good idea to try
to double an existing variable as an accumulator too...

I reworked it to:

(define (pi4 accuracy)
  (let helper ((k 0) (r 0))
    (let ((this (* (/ (expt -1 k) (expt 4 k))
                   (+ (/ 2 (+ (* 4 k) 1))
                      (/ 2 (+ (* 4 k) 2))
                      (/ 1 (+ (* 4 k) 3))))))
      (if (< (abs this) accuracy)
          (+ this r)
          (helper (+ k 1) (+ this r))))))

and just to clear up, this is not someone else's pi... :p

On Wed, Feb 15, 2012 at 5:02 PM, Matthias Felleisen
<matth...@ccs.neu.edu> wrote:
>
> If you systematically apply cps and then accumulator transformations, you get 
> this:
>
> (define (pi3 accuracy)
>  (let helper ((k 0))
>    (let ((this (formula k)))
>      (if (< (abs this) accuracy)
>          this
>          (+ this (helper (+ k 1)))))))
>
> (pi3 .1)
>
> (define (pi3-cps accuracy)
>  (let helper ((k 0) (c (lambda (x) x)))
>    (let ((this (formula k)))
>      (if (< (abs this) accuracy)
>          (c this)
>          (helper (+ k 1) (lambda (v) (c (+ this v))))))))
>
> (pi3-cps .1)
>
> (define (pi3-accu accuracy)
>  (let helper ((k 0) (c 0))
>    (let ((this (formula k)))
>      (if (< (abs this) accuracy)
>          (+ c this)
>          (helper (+ k 1) (+ c this))))))
>
> (pi3-accu .1)
>
> Now when you compare the result of that with yours:
>
> (define (pi4 accuracy)
>  (let helper ((k 1) (this (formula 0)))
>    (if (< (abs this) accuracy)
>        this
>        (helper (+ k 1) (+ this (formula k))))))
>
> you immediately see why yours fails.
>
> ;; ---
>
> I would worry about accuracy because you are switching the direction of 
> addition when you apply the accu transform, but perhaps you know why this 
> doesn't matter for your context.
>

____________________
  Racket Users list:
  http://lists.racket-lang.org/users

Reply via email to