github.com/gopherd/gonum@v0.0.4/diff/fd/example_test.go (about)

     1  // Copyright ©2016 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_test
     6  
     7  import (
     8  	"fmt"
     9  	"math"
    10  
    11  	"github.com/gopherd/gonum/diff/fd"
    12  	"github.com/gopherd/gonum/mat"
    13  )
    14  
    15  func ExampleDerivative() {
    16  	f := func(x float64) float64 {
    17  		return math.Sin(x)
    18  	}
    19  	// Compute the first derivative of f at 0 using the default settings.
    20  	fmt.Println("f'(0) ≈", fd.Derivative(f, 0, nil))
    21  	// Compute the first derivative of f at 0 using the forward approximation
    22  	// with a custom step size.
    23  	df := fd.Derivative(f, 0, &fd.Settings{
    24  		Formula: fd.Forward,
    25  		Step:    1e-3,
    26  	})
    27  	fmt.Println("f'(0) ≈", df)
    28  
    29  	f = func(x float64) float64 {
    30  		return math.Pow(math.Cos(x), 3)
    31  	}
    32  	// Compute the second derivative of f at 0 using
    33  	// the centered approximation, concurrent evaluation,
    34  	// and a known function value at x.
    35  	df = fd.Derivative(f, 0, &fd.Settings{
    36  		Formula:     fd.Central2nd,
    37  		Concurrent:  true,
    38  		OriginKnown: true,
    39  		OriginValue: f(0),
    40  	})
    41  	fmt.Println("f''(0) ≈", df)
    42  
    43  	// Output:
    44  	// f'(0) ≈ 1
    45  	// f'(0) ≈ 0.9999998333333416
    46  	// f''(0) ≈ -2.999999981767587
    47  }
    48  
    49  func ExampleJacobian() {
    50  	f := func(dst, x []float64) {
    51  		dst[0] = x[0] + 1
    52  		dst[1] = 5 * x[2]
    53  		dst[2] = 4*x[1]*x[1] - 2*x[2]
    54  		dst[3] = x[2] * math.Sin(x[0])
    55  	}
    56  	jac := mat.NewDense(4, 3, nil)
    57  	fd.Jacobian(jac, f, []float64{1, 2, 3}, &fd.JacobianSettings{
    58  		Formula:    fd.Central,
    59  		Concurrent: true,
    60  	})
    61  	fmt.Printf("J ≈ %.6v\n", mat.Formatted(jac, mat.Prefix("    ")))
    62  
    63  	// Output:
    64  	// J ≈ ⎡       1         0         0⎤
    65  	//     ⎢       0         0         5⎥
    66  	//     ⎢       0        16        -2⎥
    67  	//     ⎣ 1.62091         0  0.841471⎦
    68  }