Skip to content

Instantly share code, notes, and snippets.

@andersonfreitas
Created April 18, 2014 17:43
Show Gist options
  • Save andersonfreitas/11055882 to your computer and use it in GitHub Desktop.
Save andersonfreitas/11055882 to your computer and use it in GitHub Desktop.
derivative in js
function derivative(f) {
var h = 0.001;
return function(x) { return (f(x + h) - f(x - h)) / (2 * h); };
}
console.log(" cos(2) = " + Math.cos(2));
console.log("-sin(2) = " + Math.sin(2));
console.log("(d cos/dx)(2) = " + derivative(Math.cos)(2));
function f(x) { return Math.pow(x, 3) + 2 * x + 1; };
var x = 12.5;
console.log("[6x | x = 12.5] = " + (6 * x);
console.log("(d^2 (x^3 + 2x + 1)/dx^2)(12.5) = " +
derivative(derivative(f))(x));
@abhisack
Copy link

This is very short and gives approimately accurate value. Even no teacher in the school tells you what 'h' really is. This short piece of code has inspired me to bring more 'maths' to my JS code. Thanks!

@wdiasvargas
Copy link

@SergProduction
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment