Re: Lisp for numerical methods compared to other languages

• From: Eli Barzilay <eli@xxxxxxxxxxxx>
• Date: Tue, 11 Aug 2009 00:11:21 -0700 (PDT)

On Aug 11, 12:07 am, Jason <jason.lillywh...@xxxxxxxxx> wrote:
[...]

0.489104628447242
-2.14157580558094e-11

I hope this makes sense. I've been wanting to get this into PLT Scheme
someday. Thank you for looking!

Here's a PLT Scheme improved version of your code:

#lang scheme
(define (secant function)
(define a 9999.0)
(define b 0.00001)
(let loop ([i 100] [a a] [fa (function a)] [b b] [fb (function
b)])
(let* ([c (+ b (/ (* fb (- b a)) (- fa fb)))] [fc (function c)])
(if (or (zero? i) (< (abs (/ (- c b) c)) 0.0001))
c
(loop (sub1 i) b fb c fc)))))
(define (my-function x) (+ (* x x) (* 3.6 x) -2))
(let ([y (secant my-function)])
(values y (my-function y)))

Note that I didn't really look into how it works, I just did some
obvious transformation beginning with a direct translation of your
code:

#lang scheme

(define (secant function)
(define a 9999.0)
(define b 0.00001)
(define i 1)
(define fa (function a))
(define fb (function b))
(define fc #f)
(define c #f)
(let/ec break
(let loop ()
(when (<= i 100)
(set! c (+ b (/ (* fb (- b a)) (- fa fb))))
(set! fc (function c))
(when (< (abs (/ (- c b) c)) 0.0001) (break))
(set! a b)
(set! fa fb)
(set! b c)
(set! fb fc)