Looking for derivative script

后端 未结 6 614
情话喂你
情话喂你 2021-01-05 20:20

I am desperately looking for a JavaScript that can calculate the first derivative of a function. The function always includes only one variable, x.



        
相关标签:
6条回答
  • 2021-01-05 20:48

    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);
    }
    
    0 讨论(0)
  • 2021-01-05 20:54

    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

    0 讨论(0)
  • 2021-01-05 20:54

    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 讨论(0)
  • 2021-01-05 20:56
    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)
    
    0 讨论(0)
  • 2021-01-05 21:06

    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>

    0 讨论(0)
  • 2021-01-05 21:06

    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.

    0 讨论(0)
提交回复
热议问题