简体   繁体   English

打印带有变量替换的 mathjs 表达式

[英]Print mathjs expression with variables substituted

Is there a way to print the expression string after the scope substitutions?有没有办法在范围替换打印表达式字符串?

var n = math.compile('x * 2');
n.eval({x:2}); // returns 4

// I WISH I could do this:
n.toString({x:2}); // returns '2 * 2'

It is first necessary to understand the way that MathJS parses to Expression Trees, and the different types of nodes used.首先有必要了解 MathJS 解析为表达式树的方式,以及使用的不同类型的节点。 You can read more here in the docs .您可以在此处的文档中阅读更多内容。

Algebraic variables get parsed as SymbolNodes.代数变量被解析为符号节点。 These will need to be substituted for their values.这些将需要替换为它们的值。 The simplest way to do this would be to use the transform function, which is explained in the API further down the page given above.执行此操作的最简单方法是使用transform函数,该函数在上面给出的页面下方的 API 中进行了解释。

From the Docs来自文档

transform(callback: function)转换(回调:函数)

Recursively transform an expression tree via a transform function.通过转换函数递归转换表达式树。 Similar to Array.map, but recursively executed on all nodes in the expression tree.类似于 Array.map,但在表达式树中的所有节点上递归执行。 The callback function is a mapping function accepting a node, and returning a replacement for the node or the original node.回调函数是一个映射函数,它接受一个节点,并返回该节点或原始节点的替换。 Function callback is called as callback(node: Node, path: string, parent: Node) for every node in the tree, and must return a Node.函数回调被称为回调(节点:节点,路径:字符串,父节点:节点)对于树中的每个节点,并且必须返回一个节点。 Parameter path is a string containing a relative JSON Path.参数路径是包含相对 JSON 路径的字符串。

The transform function will stop iterating when a node is replaced by the callback function, it will not iterate over replaced nodes.当节点被回调函数替换时,转换函数将停止迭代,它不会迭代替换的节点。

For example, to replace all nodes of type SymbolNode having name 'x' with a ConstantNode with value 3:例如,要将名称为“x”的所有类型为 SymbolNode 的节点替换为值为 3 的 ConstantNode:

const node = math.parse('x^2 + 5*x')
const transformed = node.transform(function (node, path, parent) {
  if (node.isSymbolNode && node.name === 'x') {
    return new math.expression.node.ConstantNode(3)
  }
  else {
    return node
  }
})
transformed.toString() // returns '3 ^ 2 + 5 * 3'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM