File: example_test.go

package info (click to toggle)
golang-gonum-v1-gonum 0.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,792 kB
  • sloc: asm: 6,252; fortran: 5,271; sh: 377; ruby: 211; makefile: 98
file content (68 lines) | stat: -rw-r--r-- 1,751 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright ©2016 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fd_test

import (
	"fmt"
	"math"

	"gonum.org/v1/gonum/diff/fd"
	"gonum.org/v1/gonum/mat"
)

func ExampleDerivative() {
	f := func(x float64) float64 {
		return math.Sin(x)
	}
	// Compute the first derivative of f at 0 using the default settings.
	fmt.Println("f′(0) ≈", fd.Derivative(f, 0, nil))
	// Compute the first derivative of f at 0 using the forward approximation
	// with a custom step size.
	df := fd.Derivative(f, 0, &fd.Settings{
		Formula: fd.Forward,
		Step:    1e-3,
	})
	fmt.Println("f′(0) ≈", df)

	f = func(x float64) float64 {
		return math.Pow(math.Cos(x), 3)
	}
	// Compute the second derivative of f at 0 using
	// the centered approximation, concurrent evaluation,
	// and a known function value at x.
	df = fd.Derivative(f, 0, &fd.Settings{
		Formula:     fd.Central2nd,
		Concurrent:  true,
		OriginKnown: true,
		OriginValue: f(0),
	})
	fmt.Println("f′′(0) ≈", df)

	// Output:
	// f′(0) ≈ 1
	// f′(0) ≈ 0.9999998333333416
	// f′′(0) ≈ -2.999999981767587
}

func ExampleJacobian() {
	f := func(dst, x []float64) {
		dst[0] = x[0] + 1
		dst[1] = 5 * x[2]
		dst[2] = 4*x[1]*x[1] - 2*x[2]
		dst[3] = x[2] * math.Sin(x[0])
	}
	jac := mat.NewDense(4, 3, nil)
	fd.Jacobian(jac, f, []float64{1, 2, 3}, &fd.JacobianSettings{
		Formula:    fd.Central,
		Concurrent: true,
	})
	fmt.Printf("J ≈ %.6v\n", mat.Formatted(jac, mat.Prefix("    ")))

	// Output:
	// J ≈ ⎡       1         0         0⎤
	//     ⎢       0         0         5⎥
	//     ⎢       0        16        -2⎥
	//     ⎣ 1.62091         0  0.841471⎦
}