Skip to content

Instantly share code, notes, and snippets.

@thekeenant
Last active August 20, 2023 15:53
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thekeenant/4bdab56307e5b8e909f308a037a668ce to your computer and use it in GitHub Desktop.
Save thekeenant/4bdab56307e5b8e909f308a037a668ce to your computer and use it in GitHub Desktop.
Approximate the derivative of a function in Java.

Java 8 Derivative Approximation

Newton's Difference Quotient

Using lambdas'/functional programming features in Java 8, we can use some pretty concise and clear notation to approximate the derivative of a function at an x which is differentiable.

Derivatives::derive accepts a function, f(x), and returns its first derivative, f'(x), approximated using an arbitrarily low DX value, 0.0001.

Adapted from Joe Marshall's blogpost.

import java.util.function.DoubleFunction;
public class Derivatives {
// approximate the limit
private static final double DX = 0.0001;
/**
* @param f f(x), the function to derive
* @return f'(x), the derivative of the f(x)
*/
private static DoubleFunction<Double> derive(DoubleFunction<Double> f) {
return (x) -> (f.apply(x + DX) - f.apply(x)) / DX;
}
public static void main(String[] args) {
{
// f(x) = x^3
DoubleFunction<Double> cube = (x) -> x * x * x;
// f'(x) = 3 * x^2
DoubleFunction<Double> cubeDeriv = derive(cube);
// f'(2) = 3 * 2^2 = 12
assert Math.round(cubeDeriv.apply(2)) == 12.0;
// f'(3) = 3 * 3^2 = 27
assert Math.round(cubeDeriv.apply(3)) == 27.0;
// f'(4) = 3 * 4^2 = 48
assert Math.round(cubeDeriv.apply(4)) == 48.0;
}
{
// f(x) = sin(x), f'(x) = cos(x)
DoubleFunction<Double> sinDeriv = derive(Math::sin);
// f'(2π) = cos(2π) = 1.0
assert Math.round(sinDeriv.apply(Math.PI * 2)) == 1.0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment