开发者

Looking for derivative script

I am desperately looking for a JavaScript that can calculate the first derivative of a function. The function always incl开发者_StackOverflow中文版udes only one variable, x.

e.g. f(x) = x²
  f'(3) = 2x

Consequently, the script should deliver the result 6, since 2*3 = 6.

I hope you know what I mean.


function slope (f, x, dx) {
    dx = dx || .0000001;
    return (f(x+dx) - f(x)) / dx;
}

var f = function (x) { return Math.pow(x, 2); }

slope(f, 3)


Here's a Java library to help do such a thing:

http://jscl-meditor.sourceforge.net/

And another:

http://www.mathtools.net/Java/Mathematics/index.html

You can always use Rhino and import Java classes to use in your JavaScript.

Here's one for JavaScript:

http://code.google.com/p/smath/wiki/smathJavaScriptAPI


Try nerdamer .

It can do derivatives and build JavaScript functions with it.

//Derivative of x^2
var result = nerdamer('diff(x^2,x)').evaluate();
document.getElementById('text').innerHTML = "<p>f'(x)="+result.text()+'</p>';
//Build a new function
var f = result.buildFunction();
//Evalute f'(3)
document.getElementById('text').innerHTML += "<p>f'(3)="+f(3).toString()+'</p>';
<!-- Use https -->
<script src="https://nerdamer.com/js/nerdamer.core.js"></script>
<script src="https://nerdamer.com/js/Algebra.js"></script>
<script src="https://nerdamer.com/js/Calculus.js"></script>
<div id="text"></div>


I don't think there is any in javascript.

Here is some simple solution, you need to adjust the code accordingly:

var func = function(x) {return Math.pow(x, 2)}
function der(x, func, prec, isLeft){
    if(prec == undefined) prec = 0.000000001;
    var y = func(x);
    if(isLeft){
        var x1 = x - prec;
    } else {
        x1 = x + prec;
    }
    var y1 = func(x1);
    return (y1-y)/(x1-x);
}


You can do similar things using diff.js. You could do:

x = range(-10, 10, 0.01); // works only in latest browsers
f = diffXY(x, x.map(F));

which would give you the values of the derivative f of your function F at x = -10 to 10 with stepsize 0.01.


math.js looks pretty good for this job to me. Check out this example:

math.derivative('x^2', 'x')                     // Node {2 * x}
math.derivative('x^2', 'x', {simplify: false})  // Node {2 * 1 * x ^ (2 - 1)
math.derivative('sin(2x)', 'x'))                // Node {2 * cos(2 * x)}
math.derivative('2*x', 'x').evaluate()          // number 2
math.derivative('x^2', 'x').evaluate({x: 4})    // number 8
const f = math.parse('x^2')
const x = math.parse('x')
math.derivative(f, x)                           // Node {2 * x}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜