Wednesday, February 13, 2008

Time keeps on Schemin'

So one thing I'm a little bit worried about with this blog is the temptation to turn it into a semi-computer science blog. I want to keep things well rooted in math here, because math is awesome. I mean computer science is cool and all, but math is awesome, and also I think there are more computer science blogs out there than math blogs.

Still, I'm dealing with a lot of numerical analysis stuff now, the line between math and computer science is a little bit blurry. Still, because this blog is mine, I'll walk that line.

And so in the interest of math, I will now reveal to you some really cool Scheme code (just to refresh your memories, I'm using Dr. Scheme, a free Scheme interpreter, and I've been consulting The Scheme Programming Language by R. Kent Dybvig for reference) I wrote to deal with numerical analysis problems. Many people have said that Scheme should not be used for numerical analysis hw, and they are right, but that's why it's ultra-cool when you get it right.

So here's some functions:

General method applier for numerical methods requiring iteration (for generating a list of the value at several different iterations, largely for hw purposes but also so you can look at how it is converging).

(define (applymthd method fun initx tol)
(
map (lambda (iter) (method fun initx tol iter)) '(1 5 10 20 50 100 1000)
)
)

So this obviously is a pretty rough function, but I can tweak it into shape and if I do, I'll pass it along.

Here's a cheeky little function for forward distance:

(define (fordist fun n)
(
(- (fun (+ n 1)) (fun n))
)
)

Here's a less cheeky function for Aiken's terms given a function:

(define (Aitkens fun n)

(- (fun n) (/ (expt (- (fun (+ n 1)) (fun n)) 2) (+ (fun (+ n 2)) (* -2 (fun (+ n 1))) (fun n))))

)

But moving on to more sizable methods, here's an implementation of Steffensen's method:

(define (Steffensens fun initx tol iter)
(if (< iter 1)
initx
(
if

(< (abs (/ (expt (- (fun initx) initx) 2) (+ (fun (fun initx)) (* -2 (fun initx)) initx))) tol)

(- initx (/ (expt (- (fun initx) initx) 2) (+ (fun (fun initx)) (* -2 (fun initx)) initx)))

(Steffensens fun
(- initx (/ (expt (- (fun initx) initx) 2) (+ (fun (fun initx)) (* -2 (fun initx)) initx)))
tol (- iter 1))
)
)
)

More stuff: An implementation of Fixed Point Iteration:

(define (fixedpnt fun initx tol iter)
(if (< iter 1)
initx
(if (< (abs (- (fun initx) initx)) tol)
(fun initx)
(fixedpnt fun (fun initx) tol (- iter 1))
)
)
)

So that's that for now. And I'd say that's a good chunk of stuff, so that's some Scheme, but really, it's all about how to deal with numerical analysis in a quick and painless fashion made slightly more insane by using Scheme instead of any number of more saner tools.

No comments: