take the derivative of a function in javascript

In JavaScript, you can use numerical approximation to calculate the derivative of a function. Here is a simple function getDerivative that takes a function f and a number x as parameters and returns the derivative of f at x using the central difference approximation.

index.tsx
function getDerivative(f, x) {
  const h = 0.0001; // step size
  const y1 = f(x - h);
  const y2 = f(x + h);
  return (y2 - y1) / (2 * h);
}
142 chars
7 lines

To use this function, you simply need to define your function and call getDerivative with the function and the value at which you want to calculate the derivative:

index.tsx
// define the function
function myFunction(x) {
  return x * x;
}

// calculate the derivative at x = 2
const derivative = getDerivative(myFunction, 2);
console.log(derivative); // output: 4.000100000007833
207 chars
9 lines

Note that the accuracy of the approximation depends on the step size h. Smaller values of h will give a more accurate result but will also increase the computation time.

gistlibby LogSnag