central differencs in javascript

Central difference formula is used to approximate the derivative of a function. Here is a simple implementation of central difference formula in Javascript:

index.tsx
function centralDifference(x, h, func) {
  return (func(x + h) - func(x - h)) / (2 * h);
}
91 chars
4 lines

Where x is the point at which the derivative is to be approximated, h is the step size and func is the function for which the derivative is to be approximated.

Here is an example of how to use this function:

index.tsx
function f(x) {
  return Math.cos(x);
}

// Approximate the derivative of f at x=1
let derivative = centralDifference(1, 0.001, f);

console.log(derivative); // Output: -0.8414709848078965
189 chars
9 lines

In this example, the derivative of the cos function is approximated at x=1 using the centralDifference function. The result is logged to the console.

related categories

gistlibby LogSnag