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