derivative.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. import { isConstantNode, typeOf } from '../../utils/is.js';
  2. import { factory } from '../../utils/factory.js';
  3. var name = 'derivative';
  4. var dependencies = ['typed', 'config', 'parse', 'simplify', 'equal', 'isZero', 'numeric', 'ConstantNode', 'FunctionNode', 'OperatorNode', 'ParenthesisNode', 'SymbolNode'];
  5. export var createDerivative = /* #__PURE__ */factory(name, dependencies, _ref => {
  6. var {
  7. typed,
  8. config,
  9. parse,
  10. simplify,
  11. equal,
  12. isZero,
  13. numeric,
  14. ConstantNode,
  15. FunctionNode,
  16. OperatorNode,
  17. ParenthesisNode,
  18. SymbolNode
  19. } = _ref;
  20. /**
  21. * Takes the derivative of an expression expressed in parser Nodes.
  22. * The derivative will be taken over the supplied variable in the
  23. * second parameter. If there are multiple variables in the expression,
  24. * it will return a partial derivative.
  25. *
  26. * This uses rules of differentiation which can be found here:
  27. *
  28. * - [Differentiation rules (Wikipedia)](https://en.wikipedia.org/wiki/Differentiation_rules)
  29. *
  30. * Syntax:
  31. *
  32. * derivative(expr, variable)
  33. * derivative(expr, variable, options)
  34. *
  35. * Examples:
  36. *
  37. * math.derivative('x^2', 'x') // Node '2 * x'
  38. * math.derivative('x^2', 'x', {simplify: false}) // Node '2 * 1 * x ^ (2 - 1)'
  39. * math.derivative('sin(2x)', 'x')) // Node '2 * cos(2 * x)'
  40. * math.derivative('2*x', 'x').evaluate() // number 2
  41. * math.derivative('x^2', 'x').evaluate({x: 4}) // number 8
  42. * const f = math.parse('x^2')
  43. * const x = math.parse('x')
  44. * math.derivative(f, x) // Node {2 * x}
  45. *
  46. * See also:
  47. *
  48. * simplify, parse, evaluate
  49. *
  50. * @param {Node | string} expr The expression to differentiate
  51. * @param {SymbolNode | string} variable The variable over which to differentiate
  52. * @param {{simplify: boolean}} [options]
  53. * There is one option available, `simplify`, which
  54. * is true by default. When false, output will not
  55. * be simplified.
  56. * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr`
  57. */
  58. function plainDerivative(expr, variable) {
  59. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  60. simplify: true
  61. };
  62. var constNodes = {};
  63. constTag(constNodes, expr, variable.name);
  64. var res = _derivative(expr, constNodes);
  65. return options.simplify ? simplify(res) : res;
  66. }
  67. typed.addConversion({
  68. from: 'identifier',
  69. to: 'SymbolNode',
  70. convert: parse
  71. });
  72. var derivative = typed(name, {
  73. 'Node, SymbolNode': plainDerivative,
  74. 'Node, SymbolNode, Object': plainDerivative
  75. /* TODO: implement and test syntax with order of derivatives -> implement as an option {order: number}
  76. 'Node, SymbolNode, ConstantNode': function (expr, variable, {order}) {
  77. let res = expr
  78. for (let i = 0; i < order; i++) {
  79. let constNodes = {}
  80. constTag(constNodes, expr, variable.name)
  81. res = _derivative(res, constNodes)
  82. }
  83. return res
  84. }
  85. */
  86. });
  87. typed.removeConversion({
  88. from: 'identifier',
  89. to: 'SymbolNode',
  90. convert: parse
  91. });
  92. derivative._simplify = true;
  93. derivative.toTex = function (deriv) {
  94. return _derivTex.apply(null, deriv.args);
  95. };
  96. // FIXME: move the toTex method of derivative to latex.js. Difficulty is that it relies on parse.
  97. // NOTE: the optional "order" parameter here is currently unused
  98. var _derivTex = typed('_derivTex', {
  99. 'Node, SymbolNode': function NodeSymbolNode(expr, x) {
  100. if (isConstantNode(expr) && typeOf(expr.value) === 'string') {
  101. return _derivTex(parse(expr.value).toString(), x.toString(), 1);
  102. } else {
  103. return _derivTex(expr.toTex(), x.toString(), 1);
  104. }
  105. },
  106. 'Node, ConstantNode': function NodeConstantNode(expr, x) {
  107. if (typeOf(x.value) === 'string') {
  108. return _derivTex(expr, parse(x.value));
  109. } else {
  110. throw new Error("The second parameter to 'derivative' is a non-string constant");
  111. }
  112. },
  113. 'Node, SymbolNode, ConstantNode': function NodeSymbolNodeConstantNode(expr, x, order) {
  114. return _derivTex(expr.toString(), x.name, order.value);
  115. },
  116. 'string, string, number': function stringStringNumber(expr, x, order) {
  117. var d;
  118. if (order === 1) {
  119. d = '{d\\over d' + x + '}';
  120. } else {
  121. d = '{d^{' + order + '}\\over d' + x + '^{' + order + '}}';
  122. }
  123. return d + "\\left[".concat(expr, "\\right]");
  124. }
  125. });
  126. /**
  127. * Does a depth-first search on the expression tree to identify what Nodes
  128. * are constants (e.g. 2 + 2), and stores the ones that are constants in
  129. * constNodes. Classification is done as follows:
  130. *
  131. * 1. ConstantNodes are constants.
  132. * 2. If there exists a SymbolNode, of which we are differentiating over,
  133. * in the subtree it is not constant.
  134. *
  135. * @param {Object} constNodes Holds the nodes that are constant
  136. * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
  137. * @param {string} varName Variable that we are differentiating
  138. * @return {boolean} if node is constant
  139. */
  140. // TODO: can we rewrite constTag into a pure function?
  141. var constTag = typed('constTag', {
  142. 'Object, ConstantNode, string': function ObjectConstantNodeString(constNodes, node) {
  143. constNodes[node] = true;
  144. return true;
  145. },
  146. 'Object, SymbolNode, string': function ObjectSymbolNodeString(constNodes, node, varName) {
  147. // Treat other variables like constants. For reasoning, see:
  148. // https://en.wikipedia.org/wiki/Partial_derivative
  149. if (node.name !== varName) {
  150. constNodes[node] = true;
  151. return true;
  152. }
  153. return false;
  154. },
  155. 'Object, ParenthesisNode, string': function ObjectParenthesisNodeString(constNodes, node, varName) {
  156. return constTag(constNodes, node.content, varName);
  157. },
  158. 'Object, FunctionAssignmentNode, string': function ObjectFunctionAssignmentNodeString(constNodes, node, varName) {
  159. if (node.params.indexOf(varName) === -1) {
  160. constNodes[node] = true;
  161. return true;
  162. }
  163. return constTag(constNodes, node.expr, varName);
  164. },
  165. 'Object, FunctionNode | OperatorNode, string': function ObjectFunctionNodeOperatorNodeString(constNodes, node, varName) {
  166. if (node.args.length > 0) {
  167. var isConst = constTag(constNodes, node.args[0], varName);
  168. for (var i = 1; i < node.args.length; ++i) {
  169. isConst = constTag(constNodes, node.args[i], varName) && isConst;
  170. }
  171. if (isConst) {
  172. constNodes[node] = true;
  173. return true;
  174. }
  175. }
  176. return false;
  177. }
  178. });
  179. /**
  180. * Applies differentiation rules.
  181. *
  182. * @param {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} node
  183. * @param {Object} constNodes Holds the nodes that are constant
  184. * @return {ConstantNode | SymbolNode | ParenthesisNode | FunctionNode | OperatorNode} The derivative of `expr`
  185. */
  186. var _derivative = typed('_derivative', {
  187. 'ConstantNode, Object': function ConstantNodeObject(node) {
  188. return createConstantNode(0);
  189. },
  190. 'SymbolNode, Object': function SymbolNodeObject(node, constNodes) {
  191. if (constNodes[node] !== undefined) {
  192. return createConstantNode(0);
  193. }
  194. return createConstantNode(1);
  195. },
  196. 'ParenthesisNode, Object': function ParenthesisNodeObject(node, constNodes) {
  197. return new ParenthesisNode(_derivative(node.content, constNodes));
  198. },
  199. 'FunctionAssignmentNode, Object': function FunctionAssignmentNodeObject(node, constNodes) {
  200. if (constNodes[node] !== undefined) {
  201. return createConstantNode(0);
  202. }
  203. return _derivative(node.expr, constNodes);
  204. },
  205. 'FunctionNode, Object': function FunctionNodeObject(node, constNodes) {
  206. if (node.args.length !== 1) {
  207. funcArgsCheck(node);
  208. }
  209. if (constNodes[node] !== undefined) {
  210. return createConstantNode(0);
  211. }
  212. var arg0 = node.args[0];
  213. var arg1;
  214. var div = false; // is output a fraction?
  215. var negative = false; // is output negative?
  216. var funcDerivative;
  217. switch (node.name) {
  218. case 'cbrt':
  219. // d/dx(cbrt(x)) = 1 / (3x^(2/3))
  220. div = true;
  221. funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(3), new OperatorNode('^', 'pow', [arg0, new OperatorNode('/', 'divide', [createConstantNode(2), createConstantNode(3)])])]);
  222. break;
  223. case 'sqrt':
  224. case 'nthRoot':
  225. // d/dx(sqrt(x)) = 1 / (2*sqrt(x))
  226. if (node.args.length === 1) {
  227. div = true;
  228. funcDerivative = new OperatorNode('*', 'multiply', [createConstantNode(2), new FunctionNode('sqrt', [arg0])]);
  229. } else if (node.args.length === 2) {
  230. // Rearrange from nthRoot(x, a) -> x^(1/a)
  231. arg1 = new OperatorNode('/', 'divide', [createConstantNode(1), node.args[1]]);
  232. // Is a variable?
  233. constNodes[arg1] = constNodes[node.args[1]];
  234. return _derivative(new OperatorNode('^', 'pow', [arg0, arg1]), constNodes);
  235. }
  236. break;
  237. case 'log10':
  238. arg1 = createConstantNode(10);
  239. /* fall through! */
  240. case 'log':
  241. if (!arg1 && node.args.length === 1) {
  242. // d/dx(log(x)) = 1 / x
  243. funcDerivative = arg0.clone();
  244. div = true;
  245. } else if (node.args.length === 1 && arg1 || node.args.length === 2 && constNodes[node.args[1]] !== undefined) {
  246. // d/dx(log(x, c)) = 1 / (x*ln(c))
  247. funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('log', [arg1 || node.args[1]])]);
  248. div = true;
  249. } else if (node.args.length === 2) {
  250. // d/dx(log(f(x), g(x))) = d/dx(log(f(x)) / log(g(x)))
  251. return _derivative(new OperatorNode('/', 'divide', [new FunctionNode('log', [arg0]), new FunctionNode('log', [node.args[1]])]), constNodes);
  252. }
  253. break;
  254. case 'pow':
  255. constNodes[arg1] = constNodes[node.args[1]];
  256. // Pass to pow operator node parser
  257. return _derivative(new OperatorNode('^', 'pow', [arg0, node.args[1]]), constNodes);
  258. case 'exp':
  259. // d/dx(e^x) = e^x
  260. funcDerivative = new FunctionNode('exp', [arg0.clone()]);
  261. break;
  262. case 'sin':
  263. // d/dx(sin(x)) = cos(x)
  264. funcDerivative = new FunctionNode('cos', [arg0.clone()]);
  265. break;
  266. case 'cos':
  267. // d/dx(cos(x)) = -sin(x)
  268. funcDerivative = new OperatorNode('-', 'unaryMinus', [new FunctionNode('sin', [arg0.clone()])]);
  269. break;
  270. case 'tan':
  271. // d/dx(tan(x)) = sec(x)^2
  272. funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sec', [arg0.clone()]), createConstantNode(2)]);
  273. break;
  274. case 'sec':
  275. // d/dx(sec(x)) = sec(x)tan(x)
  276. funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tan', [arg0.clone()])]);
  277. break;
  278. case 'csc':
  279. // d/dx(csc(x)) = -csc(x)cot(x)
  280. negative = true;
  281. funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('cot', [arg0.clone()])]);
  282. break;
  283. case 'cot':
  284. // d/dx(cot(x)) = -csc(x)^2
  285. negative = true;
  286. funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csc', [arg0.clone()]), createConstantNode(2)]);
  287. break;
  288. case 'asin':
  289. // d/dx(asin(x)) = 1 / sqrt(1 - x^2)
  290. div = true;
  291. funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]);
  292. break;
  293. case 'acos':
  294. // d/dx(acos(x)) = -1 / sqrt(1 - x^2)
  295. div = true;
  296. negative = true;
  297. funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])]);
  298. break;
  299. case 'atan':
  300. // d/dx(atan(x)) = 1 / (x^2 + 1)
  301. div = true;
  302. funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]);
  303. break;
  304. case 'asec':
  305. // d/dx(asec(x)) = 1 / (|x|*sqrt(x^2 - 1))
  306. div = true;
  307. funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
  308. break;
  309. case 'acsc':
  310. // d/dx(acsc(x)) = -1 / (|x|*sqrt(x^2 - 1))
  311. div = true;
  312. negative = true;
  313. funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
  314. break;
  315. case 'acot':
  316. // d/dx(acot(x)) = -1 / (x^2 + 1)
  317. div = true;
  318. negative = true;
  319. funcDerivative = new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)]);
  320. break;
  321. case 'sinh':
  322. // d/dx(sinh(x)) = cosh(x)
  323. funcDerivative = new FunctionNode('cosh', [arg0.clone()]);
  324. break;
  325. case 'cosh':
  326. // d/dx(cosh(x)) = sinh(x)
  327. funcDerivative = new FunctionNode('sinh', [arg0.clone()]);
  328. break;
  329. case 'tanh':
  330. // d/dx(tanh(x)) = sech(x)^2
  331. funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('sech', [arg0.clone()]), createConstantNode(2)]);
  332. break;
  333. case 'sech':
  334. // d/dx(sech(x)) = -sech(x)tanh(x)
  335. negative = true;
  336. funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('tanh', [arg0.clone()])]);
  337. break;
  338. case 'csch':
  339. // d/dx(csch(x)) = -csch(x)coth(x)
  340. negative = true;
  341. funcDerivative = new OperatorNode('*', 'multiply', [node, new FunctionNode('coth', [arg0.clone()])]);
  342. break;
  343. case 'coth':
  344. // d/dx(coth(x)) = -csch(x)^2
  345. negative = true;
  346. funcDerivative = new OperatorNode('^', 'pow', [new FunctionNode('csch', [arg0.clone()]), createConstantNode(2)]);
  347. break;
  348. case 'asinh':
  349. // d/dx(asinh(x)) = 1 / sqrt(x^2 + 1)
  350. div = true;
  351. funcDerivative = new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]);
  352. break;
  353. case 'acosh':
  354. // d/dx(acosh(x)) = 1 / sqrt(x^2 - 1); XXX potentially only for x >= 1 (the real spectrum)
  355. div = true;
  356. funcDerivative = new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])]);
  357. break;
  358. case 'atanh':
  359. // d/dx(atanh(x)) = 1 / (1 - x^2)
  360. div = true;
  361. funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]);
  362. break;
  363. case 'asech':
  364. // d/dx(asech(x)) = -1 / (x*sqrt(1 - x^2))
  365. div = true;
  366. negative = true;
  367. funcDerivative = new OperatorNode('*', 'multiply', [arg0.clone(), new FunctionNode('sqrt', [new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])])])]);
  368. break;
  369. case 'acsch':
  370. // d/dx(acsch(x)) = -1 / (|x|*sqrt(x^2 + 1))
  371. div = true;
  372. negative = true;
  373. funcDerivative = new OperatorNode('*', 'multiply', [new FunctionNode('abs', [arg0.clone()]), new FunctionNode('sqrt', [new OperatorNode('+', 'add', [new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)]), createConstantNode(1)])])]);
  374. break;
  375. case 'acoth':
  376. // d/dx(acoth(x)) = -1 / (1 - x^2)
  377. div = true;
  378. negative = true;
  379. funcDerivative = new OperatorNode('-', 'subtract', [createConstantNode(1), new OperatorNode('^', 'pow', [arg0.clone(), createConstantNode(2)])]);
  380. break;
  381. case 'abs':
  382. // d/dx(abs(x)) = abs(x)/x
  383. funcDerivative = new OperatorNode('/', 'divide', [new FunctionNode(new SymbolNode('abs'), [arg0.clone()]), arg0.clone()]);
  384. break;
  385. case 'gamma': // Needs digamma function, d/dx(gamma(x)) = gamma(x)digamma(x)
  386. default:
  387. throw new Error('Function "' + node.name + '" is not supported by derivative, or a wrong number of arguments is passed');
  388. }
  389. var op, func;
  390. if (div) {
  391. op = '/';
  392. func = 'divide';
  393. } else {
  394. op = '*';
  395. func = 'multiply';
  396. }
  397. /* Apply chain rule to all functions:
  398. F(x) = f(g(x))
  399. F'(x) = g'(x)*f'(g(x)) */
  400. var chainDerivative = _derivative(arg0, constNodes);
  401. if (negative) {
  402. chainDerivative = new OperatorNode('-', 'unaryMinus', [chainDerivative]);
  403. }
  404. return new OperatorNode(op, func, [chainDerivative, funcDerivative]);
  405. },
  406. 'OperatorNode, Object': function OperatorNodeObject(node, constNodes) {
  407. if (constNodes[node] !== undefined) {
  408. return createConstantNode(0);
  409. }
  410. if (node.op === '+') {
  411. // d/dx(sum(f(x)) = sum(f'(x))
  412. return new OperatorNode(node.op, node.fn, node.args.map(function (arg) {
  413. return _derivative(arg, constNodes);
  414. }));
  415. }
  416. if (node.op === '-') {
  417. // d/dx(+/-f(x)) = +/-f'(x)
  418. if (node.isUnary()) {
  419. return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes)]);
  420. }
  421. // Linearity of differentiation, d/dx(f(x) +/- g(x)) = f'(x) +/- g'(x)
  422. if (node.isBinary()) {
  423. return new OperatorNode(node.op, node.fn, [_derivative(node.args[0], constNodes), _derivative(node.args[1], constNodes)]);
  424. }
  425. }
  426. if (node.op === '*') {
  427. // d/dx(c*f(x)) = c*f'(x)
  428. var constantTerms = node.args.filter(function (arg) {
  429. return constNodes[arg] !== undefined;
  430. });
  431. if (constantTerms.length > 0) {
  432. var nonConstantTerms = node.args.filter(function (arg) {
  433. return constNodes[arg] === undefined;
  434. });
  435. var nonConstantNode = nonConstantTerms.length === 1 ? nonConstantTerms[0] : new OperatorNode('*', 'multiply', nonConstantTerms);
  436. var newArgs = constantTerms.concat(_derivative(nonConstantNode, constNodes));
  437. return new OperatorNode('*', 'multiply', newArgs);
  438. }
  439. // Product Rule, d/dx(f(x)*g(x)) = f'(x)*g(x) + f(x)*g'(x)
  440. return new OperatorNode('+', 'add', node.args.map(function (argOuter) {
  441. return new OperatorNode('*', 'multiply', node.args.map(function (argInner) {
  442. return argInner === argOuter ? _derivative(argInner, constNodes) : argInner.clone();
  443. }));
  444. }));
  445. }
  446. if (node.op === '/' && node.isBinary()) {
  447. var arg0 = node.args[0];
  448. var arg1 = node.args[1];
  449. // d/dx(f(x) / c) = f'(x) / c
  450. if (constNodes[arg1] !== undefined) {
  451. return new OperatorNode('/', 'divide', [_derivative(arg0, constNodes), arg1]);
  452. }
  453. // Reciprocal Rule, d/dx(c / f(x)) = -c(f'(x)/f(x)^2)
  454. if (constNodes[arg0] !== undefined) {
  455. return new OperatorNode('*', 'multiply', [new OperatorNode('-', 'unaryMinus', [arg0]), new OperatorNode('/', 'divide', [_derivative(arg1, constNodes), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])])]);
  456. }
  457. // Quotient rule, d/dx(f(x) / g(x)) = (f'(x)g(x) - f(x)g'(x)) / g(x)^2
  458. return new OperatorNode('/', 'divide', [new OperatorNode('-', 'subtract', [new OperatorNode('*', 'multiply', [_derivative(arg0, constNodes), arg1.clone()]), new OperatorNode('*', 'multiply', [arg0.clone(), _derivative(arg1, constNodes)])]), new OperatorNode('^', 'pow', [arg1.clone(), createConstantNode(2)])]);
  459. }
  460. if (node.op === '^' && node.isBinary()) {
  461. var _arg = node.args[0];
  462. var _arg2 = node.args[1];
  463. if (constNodes[_arg] !== undefined) {
  464. // If is secretly constant; 0^f(x) = 1 (in JS), 1^f(x) = 1
  465. if (isConstantNode(_arg) && (isZero(_arg.value) || equal(_arg.value, 1))) {
  466. return createConstantNode(0);
  467. }
  468. // d/dx(c^f(x)) = c^f(x)*ln(c)*f'(x)
  469. return new OperatorNode('*', 'multiply', [node, new OperatorNode('*', 'multiply', [new FunctionNode('log', [_arg.clone()]), _derivative(_arg2.clone(), constNodes)])]);
  470. }
  471. if (constNodes[_arg2] !== undefined) {
  472. if (isConstantNode(_arg2)) {
  473. // If is secretly constant; f(x)^0 = 1 -> d/dx(1) = 0
  474. if (isZero(_arg2.value)) {
  475. return createConstantNode(0);
  476. }
  477. // Ignore exponent; f(x)^1 = f(x)
  478. if (equal(_arg2.value, 1)) {
  479. return _derivative(_arg, constNodes);
  480. }
  481. }
  482. // Elementary Power Rule, d/dx(f(x)^c) = c*f'(x)*f(x)^(c-1)
  483. var powMinusOne = new OperatorNode('^', 'pow', [_arg.clone(), new OperatorNode('-', 'subtract', [_arg2, createConstantNode(1)])]);
  484. return new OperatorNode('*', 'multiply', [_arg2.clone(), new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), powMinusOne])]);
  485. }
  486. // Functional Power Rule, d/dx(f^g) = f^g*[f'*(g/f) + g'ln(f)]
  487. return new OperatorNode('*', 'multiply', [new OperatorNode('^', 'pow', [_arg.clone(), _arg2.clone()]), new OperatorNode('+', 'add', [new OperatorNode('*', 'multiply', [_derivative(_arg, constNodes), new OperatorNode('/', 'divide', [_arg2.clone(), _arg.clone()])]), new OperatorNode('*', 'multiply', [_derivative(_arg2, constNodes), new FunctionNode('log', [_arg.clone()])])])]);
  488. }
  489. throw new Error('Operator "' + node.op + '" is not supported by derivative, or a wrong number of arguments is passed');
  490. }
  491. });
  492. /**
  493. * Ensures the number of arguments for a function are correct,
  494. * and will throw an error otherwise.
  495. *
  496. * @param {FunctionNode} node
  497. */
  498. function funcArgsCheck(node) {
  499. // TODO add min, max etc
  500. if ((node.name === 'log' || node.name === 'nthRoot' || node.name === 'pow') && node.args.length === 2) {
  501. return;
  502. }
  503. // There should be an incorrect number of arguments if we reach here
  504. // Change all args to constants to avoid unidentified
  505. // symbol error when compiling function
  506. for (var i = 0; i < node.args.length; ++i) {
  507. node.args[i] = createConstantNode(0);
  508. }
  509. node.compile().evaluate();
  510. throw new Error('Expected TypeError, but none found');
  511. }
  512. /**
  513. * Helper function to create a constant node with a specific type
  514. * (number, BigNumber, Fraction)
  515. * @param {number} value
  516. * @param {string} [valueType]
  517. * @return {ConstantNode}
  518. */
  519. function createConstantNode(value, valueType) {
  520. return new ConstantNode(numeric(value, valueType || config.number));
  521. }
  522. return derivative;
  523. });