
Stand-alone code for numerical computing - fogus
http://www.johndcook.com/stand_alone_code.html
======
kwantam
In general, using a Taylor series approximation for a function near points
where the argument disappears much faster than the function's value is a nice
idea. You have to be careful to specify how much precision you're going after,
though: using only two terms of the Taylor series isn't particularly precise.

I've gone faaaar the other way (using way too many terms of the Taylor series)
to get stupid amounts of precision from such functions in the past. Here's an
example in Scheme:

    
    
        (define n1toN (fromTo 1 100))
          ; where fromTo returns a list from $< to $>
          ; 100 terms is insanely overkill
        (define invFacts (scanl (lambda (y x) (/ y x)) 1 n1toN))
          ; scanl is foldl that builds a list of intermediate results
    
          ; use taylor expansion of e^x near 0 to reduce numerical error
          ; empirically, the break-even point for precision is near 0.19
        (define (expm1 x)
          (if (< (magnitude x) 0.19)
              (letrec ((expm1Hlp
                       (lambda (expts iFacts)
                         (if (null? expts) 0
                             (+ (* (expt x (car expts)) (car iFacts))
                                (expm1Hlp (cdr expts) (cdr iFacts)))))))
                      (+ x (expm1Hlp (cdr n1toN) (cdr invFacts))))
              (- (exp x) 1)))
    
    

A really fun one is the Taylor expansion of tanh(x)[1], which includes the
Bernoulli numbers. Thanks to Akiyama and Tanigawa[2], there's a cool and
simple (not computationally---it's O(n^2)) way of generating the first N
Bernoulli numbers.

[1]
[http://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin...](http://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin_series_of_some_common_functions)

[2] [http://www.cs.uwaterloo.ca/journals/JIS/VOL3/KANEKO/AT-
kanek...](http://www.cs.uwaterloo.ca/journals/JIS/VOL3/KANEKO/AT-kaneko.pdf)

