github.com/jingcheng-WU/gonum@v0.9.1-0.20210323123734-f1a2a11a8f7b/diff/fd/laplacian_test.go (about)

     1  // Copyright ©2017 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 fd
     6  
     7  import (
     8  	"testing"
     9  
    10  	"github.com/jingcheng-WU/gonum/floats/scalar"
    11  	"github.com/jingcheng-WU/gonum/mat"
    12  )
    13  
    14  func TestLaplacian(t *testing.T) {
    15  	t.Parallel()
    16  	for cas, test := range hessianTestCases() {
    17  		// Modify the test cases where the formula is set.
    18  		settings := test.settings
    19  		if settings != nil && !settings.Formula.isZero() {
    20  			settings.Formula = Forward2nd
    21  		}
    22  
    23  		n := len(test.x)
    24  		got := Laplacian(test.h.Func, test.x, test.settings)
    25  		hess := mat.NewSymDense(n, nil)
    26  		test.h.Hess(hess, test.x)
    27  		var want float64
    28  		for i := 0; i < n; i++ {
    29  			want += hess.At(i, i)
    30  		}
    31  		if !scalar.EqualWithinAbsOrRel(got, want, test.tol, test.tol) {
    32  			t.Errorf("Cas %d: Laplacian mismatch. got %v, want %v", cas, got, want)
    33  		}
    34  
    35  		// Test that concurrency works.
    36  		if settings == nil {
    37  			settings = &Settings{}
    38  		}
    39  		settings.Concurrent = true
    40  		got2 := Laplacian(test.h.Func, test.x, settings)
    41  		if !scalar.EqualWithinAbsOrRel(got, got2, 1e-5, 1e-5) {
    42  			t.Errorf("Cas %d: Laplacian mismatch. got %v, want %v", cas, got2, got)
    43  		}
    44  	}
    45  }