Skip to content

Instantly share code, notes, and snippets.

@shawnsmithdev
Created May 24, 2016 20:00
Show Gist options
  • Save shawnsmithdev/9a2a0cd0caff202ef9aedb9bdcd4eecd to your computer and use it in GitHub Desktop.
Save shawnsmithdev/9a2a0cd0caff202ef9aedb9bdcd4eecd to your computer and use it in GitHub Desktop.
Numerical Integration
package main
import (
"fmt"
"math"
)
// Simpson's Rule for numerical integration of f from a to b using n steps
// Port of python code: http://stackoverflow.com/questions/16001157/simpsons-rule-in-python
func simpsons(f func(float64) float64, a, b float64, n int) float64 {
h := (b - a) / float64(n)
k := 0.0
x := a + h
for i := 1; i < (n/2)+1; i++ {
k += 4 * f(x)
x += 2 * h
}
x = a + 2*h
for i := 1; i < n/2; i++ {
k += 2 * f(x)
x += 2 * h
}
return (h / 3) * (f(a) + f(b) + k)
}
func main() {
// Should be e-1 (~1.7183)
fmt.Println(simpsons(math.Exp, 0.0, 1.0, 100))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment