Anonymous user
Numerical integration/Gauss-Legendre Quadrature: Difference between revisions
Numerical integration/Gauss-Legendre Quadrature (view source)
Revision as of 16:38, 19 May 2013
, 11 years ago→{{header|Racket}}
Line 734:
Computation of the Legendre polynomials and derivatives:
<lang
(define (LegendreP n x)
(let compute ([n n] [Pn-1 x] [Pn-2 1])
Line 753:
Computation of the Legendre polynomial roots:
<lang
(define (LegendreP-root n i)
; newton-raphson step
(define (newton-step x)
(- x (/ (LegendreP n x) (
; initial guess
(define x0 (cos (* pi (/ (- i 1/4) (+ n 1/2)))))
Line 766:
(if (< (abs (/ (- x′ x) (+ x′ x))) 1e-15)
x′
(next (newton-step x′)
</lang>
Computation of Gauss-Legendre nodes and weights
<lang
(define (Gauss-Legendre-quadrature n)
;; positive roots
(define roots
(for/list ([i (in-range (floor (/ n 2)))])
(LegendreP-root n (+ i 1))))
;; weights for positive roots
(define weights
(for/list ([x (in-list roots)])
(/ 2 (- 1 (sqr x)) (sqr (LegendreP′ n x)))))
;; all roots and weights
(values (append (map - roots)
(
</lang>
Integration using Gauss-Legendre quadratures:
<lang
(define (integrate f a b #:nodes (n 5))
(define m (/ (+ a b) 2))
(define d (/ (- b a) 2))
(define-values
(define (g x) (f (+ m (* d x))))
(* d (+ (apply + (map * w (map g x))))))
</lang>
Usage:
<lang
> (Gauss-Legendre-quadrature 5)
'(-0.906179845938664 -0.5384693101056831 0 0.5384693101056831 0.906179845938664)
Line 818 ⟶ 817:
Accuracy of the method:
<lang
> (require plot)
> (parameterize ([plot-x-label "Number of Gaussian nodes"]
[plot-y-label "Integration error"]
[plot-y-transform
[plot-y-ticks (log-ticks #:base 10)])
(plot (points (for/list ([n (in-range 2 11)])
(list n (abs (- (integrate exp -3 3 #:nodes n)▼
(- (exp 3) (exp -3)))))))))
▲ (list n (abs (- (integrate exp -3 3 #:nodes n)
▲ (- (exp 3) (exp -3)))))))))
</lang>
[[File:gauss.png]]
|