github.com/jingcheng-WU/gonum@v0.9.1-0.20210323123734-f1a2a11a8f7b/integrate/quad/legendre_test.go (about) 1 // Copyright ©2015 The Gonum Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package quad 6 7 import ( 8 "math" 9 "testing" 10 11 "github.com/jingcheng-WU/gonum/floats" 12 "github.com/jingcheng-WU/gonum/floats/scalar" 13 ) 14 15 func TestLegendre(t *testing.T) { 16 t.Parallel() 17 for i, test := range []struct { 18 f func(float64) float64 19 min, max float64 20 n []int 21 tol []float64 22 ans float64 23 }{ 24 // Tolerances determined from intuition and a bit of post-hoc tweaking. 25 { 26 f: func(x float64) float64 { return math.Exp(x) }, 27 min: -3, 28 max: 5, 29 n: []int{3, 4, 6, 7, 15, 16, 300, 301}, 30 tol: []float64{5e-2, 5e-3, 5e-6, 1e-7, 1e-14, 1e-14, 1e-14, 1e-14}, 31 ans: math.Exp(5) - math.Exp(-3), 32 }, 33 } { 34 for j, n := range test.n { 35 ans := Fixed(test.f, test.min, test.max, n, Legendre{}, 0) 36 if !scalar.EqualWithinAbsOrRel(ans, test.ans, test.tol[j], test.tol[j]) { 37 t.Errorf("Mismatch. Case = %d, n = %d. Want %v, got %v", i, n, test.ans, ans) 38 } 39 ans2 := Fixed(test.f, test.min, test.max, n, Legendre{}, 3) 40 if !scalar.EqualWithinAbsOrRel(ans2, test.ans, test.tol[j], test.tol[j]) { 41 t.Errorf("Mismatch concurrent. Case = %d, n = %d. Want %v, got %v", i, n, test.ans, ans) 42 } 43 } 44 } 45 } 46 47 func TestLegendreSingle(t *testing.T) { 48 t.Parallel() 49 for c, test := range []struct { 50 n int 51 min, max float64 52 }{ 53 { 54 n: 100, 55 min: -1, 56 max: 1, 57 }, 58 { 59 n: 50, 60 min: -3, 61 max: -1, 62 }, 63 { 64 n: 1000, 65 min: 2, 66 max: 7, 67 }, 68 } { 69 l := Legendre{} 70 n := test.n 71 xs := make([]float64, n) 72 weights := make([]float64, n) 73 l.FixedLocations(xs, weights, test.min, test.max) 74 75 xsSingle := make([]float64, n) 76 weightsSingle := make([]float64, n) 77 for i := range xsSingle { 78 xsSingle[i], weightsSingle[i] = l.FixedLocationSingle(n, i, test.min, test.max) 79 } 80 if !floats.Equal(xs, xsSingle) { 81 t.Errorf("Case %d: xs mismatch batch and single", c) 82 } 83 if !floats.Equal(weights, weightsSingle) { 84 t.Errorf("Case %d: weights mismatch batch and single", c) 85 } 86 } 87 }