Skip to content

Instantly share code, notes, and snippets.

@MattRoelle
Last active December 27, 2015 13:09
Show Gist options
  • Save MattRoelle/7331081 to your computer and use it in GitHub Desktop.
Save MattRoelle/7331081 to your computer and use it in GitHub Desktop.
Basic implementation of derivatives and limits in JavaScript Extends the Function object
console.clear();
Function.prototype.limit = function (x, accuracy) {
var f = this; // for clarity
var C; // constant
if (accuracy === undefined) {
accuracy = 6; // if no accuracy is passed, check to the sixth decimal
}
function compareRSLwithLSL(i) {
C = 1 / i;
/*
* Numerically analyze the limit by comparing the RSL with the LSL
* The accuracy of the comparison will be determined by the accuracy parameter
* (default to the 1000th decimal place)
*/
if (i >= Math.pow(10, accuracy)) {
return (f(x + C)).toFixed(accuracy - 1);
} else {
if (Math.abs(f(x + C) - f(x - C)) <= (1 / (i / 100))) {
return compareRSLwithLSL(i * 10);
} else {
return NaN;
}
}
}
return compareRSLwithLSL(Math.pow(10, accuracy - 2));
};
Function.prototype.msec = function (x1, x2) {
/* q
* Return the slope of the secant line
* Uses the basic slope formula
* y2 - y1 / x2 - x1
*/
var f = this; // for clarity
return (f(x1) - f(x2)) / (x1 - x2);
}
Function.prototype.derivative = function (accuracy) {
/*
* Functional that returns the derivative
* Based on a secant line taken at two points that are extremely
* close to one another
*/
var f = this; // for clarity
if (accuracy === undefined) {
accuracy = 6; // if no accuracy is passed, check to the sixth decimal
}
return function (x) {
if (isNaN(f.limit(x, accuracy))) {
return NaN;
} else {
return f.msec(x, x + (1 / Math.pow(10, accuracy))).toFixed(accuracy - 1);
}
};
};
function quadratic(x) {
// f(x) = x^2
return x * x;
};
function peacewise(x) {
//f(x) = { 5 if x > 2
// 10 if x <= 2
if (x > 2) {
return 5;
} else {
return 10;
}
};
var C = 2; // constant
console.log(quadratic.limit(C)); // evaluates to 4
console.log(peacewise.limit(C)); // evaluates to NaN, the JavaScript equivelent of DNE
console.log(quadratic.derivative()(C)); // evaluates to 4
console.log(peacewise.derivative()(C)); // evalutaes to NaN, the peacewise defined function is
// not differntiable at 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment