github.com/jingcheng-WU/gonum@v0.9.1-0.20210323123734-f1a2a11a8f7b/integrate/trapezoidal.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 integrate 6 7 import "sort" 8 9 // Trapezoidal returns an approximate value of the integral 10 // \int_a^b f(x) dx 11 // computed using the trapezoidal rule. The function f is given as a slice of 12 // samples evaluated at locations in x, that is, 13 // f[i] = f(x[i]), x[0] = a, x[len(x)-1] = b 14 // The slice x must be sorted in strictly increasing order. x and f must be of 15 // equal length and the length must be at least 2. 16 // 17 // The trapezoidal rule approximates f by a piecewise linear function and 18 // estimates 19 // \int_x[i]^x[i+1] f(x) dx 20 // as 21 // (x[i+1] - x[i]) * (f[i] + f[i+1])/2 22 // More details on the trapezoidal rule can be found at: 23 // https://en.wikipedia.org/wiki/Trapezoidal_rule 24 func Trapezoidal(x, f []float64) float64 { 25 n := len(x) 26 switch { 27 case len(f) != n: 28 panic("integrate: slice length mismatch") 29 case n < 2: 30 panic("integrate: input data too small") 31 case !sort.Float64sAreSorted(x): 32 panic("integrate: input must be sorted") 33 } 34 35 integral := 0.0 36 for i := 0; i < n-1; i++ { 37 integral += 0.5 * (x[i+1] - x[i]) * (f[i+1] + f[i]) 38 } 39 40 return integral 41 }