take the derivative of a function in go

Go language provides a math package that includes many mathematical functions, including differentiation. We can use the Deriv function provided by the math package to compute the derivative of a function.

Here's an example:

main.go
package main

import (
    "fmt"
    "math"
)

func f(x float64) float64 {
    return math.Pow(x, 2) + 2*x + 1 // example function f(x) = x^2 + 2x + 1
}

func main() {
    x := 2.0 // the value of x at which we want to evaluate the derivative
    df := math.Deriv(f, x) // calculate the derivative of f at x
    fmt.Printf("The derivative of f(x) = x^2 + 2x + 1 at x = %.2f is %.2f", x, df)
}
393 chars
17 lines

This program will output:

main.go
The derivative of f(x) = x^2 + 2x + 1 at x = 2.00 is 6.00
58 chars
2 lines

Note that the Deriv function calculates the derivative numerically using a five-point stencil method. Therefore, we need to provide a function f which takes a float64 argument and returns a float64 value.

gistlibby LogSnag