How to use the derivative function from mathjs

Find comprehensive JavaScript mathjs.derivative code examples handpicked from public code repositorys.

mathjs.derivative is a function in the Math.js library that calculates the derivative of a mathematical expression with respect to a given variable.

18
19
20
21
22
23
24
25
26
27
case "eval":
    try { done = await math.evaluate(args.slice(1).join(" ")); } catch(err) {done = "Evaluation Error"; NorthClient.storage.error(err);}
    break;
case "derivative":
case "ddx":
    try { done = await math.derivative(args.slice(1).join(" "), "x").compile().evaluate(); } catch(err) {done = "Differentiation Error"; NorthClient.storage.error(err);}
    break;
case "rationalize":
case "rat":
    try { done = math.rationalize(args.slice(1).join(" ")).toString(); } catch(err) {done = "Rationalization Error"; NorthClient.storage.error(err);}
fork icon1
star icon1
watch icon0

+ 3 other calls in file

35
36
37
38
39
40
41
42
43
input.keyup(function (event) {
    console.log("RUNNNING!");
    var derivativeIntial = input.val();
    console.log("B");
    console.log(derivative(derivativeIntial, 'x').toString());
    var final = derivative(derivativeIntial, 'x').toString();
    console.log("C");
    document.getElementById("derivativeOutput").innerHTML = final; 
}); 
fork icon0
star icon1
watch icon0

+ 3 other calls in file

How does mathjs.derivative work?

mathjs.derivative is a function provided by the Math.js library that computes the symbolic derivative of a mathematical expression with respect to a given variable, using differentiation rules such as the chain rule, product rule, quotient rule, and power rule. The function takes two arguments: the first is the expression to differentiate, and the second is the variable with respect to which to differentiate. The resulting derivative expression can then be manipulated and evaluated using other Math.js functions.

7
8
9
10
11
12
13
14
15
16
17
18
19
20


const injector = new Injector(math, 'derivative', __filename, 'SSE23-derivative');


console.log(math.derivative('x^2', 'x'));


let a = math.derivative('x^2', 'x');
let b = math.derivative('sin(2x)', 'x')


console.log(a)
console.log(b)
fork icon0
star icon1
watch icon0

46
47
48
49
50
51
52
53
54
55

if(checkderivative > -1) {
    var derivativeof = args.substring((checkderivative+derivative.length), args.length);
    args = args.substring(0, checkderivative);

    result = math.derivative(args, derivativeof).toString();
}

var simplify = 'simplify';
var checksimplify = args.indexOf(simplify);
fork icon0
star icon1
watch icon0

Ai Example

1
2
3
4
5
6
7
const math = require("mathjs");

const expr = "x^2";
const varName = "x";

const derivative = math.derivative(expr, varName);
console.log(derivative.toString()); // outputs "2 * x"

In this example, we use mathjs to calculate the derivative of x^2 with respect to x. We pass in the expression x^2 and the variable name x to the math.derivative() function. The function returns a new expression that represents the derivative of the input expression with respect to the input variable. Finally, we convert the resulting expression to a string so that we can print it to the console. The output of this example will be 2 * x, which is the derivative of x^2 with respect to x.

175
176
177
178
179
180
181
182
183
184
let xovar = parseInt(xo);

for (let i=0; i<iteration; i++) {
  const fxo = f.replaceAll(unknown, xovar < 0 ? '(' + xovar + ')' : xovar);
  const fxoa = math.evaluate(fxo);
  const dfx = math.derivative(f, unknown).toString();
  const dfxo = dfx.replaceAll(unknown, xovar < 0 ? '(' + xovar + ')' : xovar);
  const dfxoa = math.evaluate(dfxo);
  const xn = xovar - (fxoa / dfxoa);
  const fxn = f.replaceAll(unknown, xn);
fork icon0
star icon0
watch icon1

+ 83 other calls in file

87
88
89
90
91
92
93
94
95
96
97
  }
}
// Deriva Expresiones
function deriveExp(exp) {
  console.log(exp);
  return math.derivative(exp[0], exp[1]);
}


// Genera un árbol con los datos del archivo xml
function StructTree(json, padre) {
fork icon0
star icon0
watch icon1

113
114
115
116
117
118
119
120
121
122
123
  }
  return xInicial;
}


function derivarFuncion(funcion) {
  return derivative(funcion, "x").toString();
}


// newtonForm.addEventListener("submit", onSubmit);
fork icon0
star icon0
watch icon0

41
42
43
44
45
46
47
48
49
50
51
52
}


// Função para Derivadas
function differentiate() {
  let x = document.getElementById("calc").value;
  let y = math.derivative(x, 'x').toString();
  document.getElementById("calc").value = y;
}


// Função para Integrais
fork icon0
star icon0
watch icon0

+ 2 other calls in file

60
61
62
63
64
65
66
67
68
69
if (subIntervals !== "-1") {
  var potentialError = math.abs(math.evaluate(`((${end} - ${start})^3)/(24*(${subIntervals}^2))`));
  totalText += ("\n**The potential error formula for this problem is:** ```|max(f''(x))| * " + potentialError + "```");

  //Get derivative of function
  var derivative = math.derivative(math.derivative(functionToCalculate, "x"), "x").toString();

  //Plug in numbers from -999 to 9999 for x in derivative and find maximum value 
  var max = -999;
  console.log(derivative.replace(/x/g, `(${i})`));
fork icon0
star icon0
watch icon0

+ 6 other calls in file

27
28
29
30
31
32
33
34
35
36
    };
};

/* Let renderer load first */
const renderer = require('../../../../renderer.js');
const derivativeSymbolic = math.derivative;

/**
 * Compute a derivative
 * @param {string} expression Expression, ie 'x^2'
fork icon0
star icon0
watch icon5

+ 13 other calls in file