我正在制作一个应用程序,我想在其中使用数学和物理的公式/方程。我在每个公式中都包含了一个计算器部分,以便用户能够插入他的值并获得方程的结果。问题是,我需要为每个未知变量重新格式化方程,是否有脚本,或者至少有某种算法能够做到这一点?
我正在使用 MathJax 反应本机模块来显示表达式和 javascripteval
函数来评估它们。
我找到了 algebra.js 插件,但它似乎不包含我需要的任何东西,与 github 上的“nerdamer”js 插件相同。
我用这个函数来评估方程,variable_finding
是方程“左侧”的变量,代码的其余部分负责“右侧”
calculateSolution = (variable_finding) => {
equation = this.state.input_equation
vars = []
for (let i = 0; i < this.state.variables.length; i++) {
if (this.state.variables[i].variable !=
variable_finding.variable) {
vars.push([
this.state.variables[i].variable,
'£' + this.state.variables[i].variable + '£',
this.state.variables[i].value
])
}
}
for (let i = 0; i < vars.length; i++) {
equation = equation.replace(vars[i][1], vars[i][2]);
}
this.setState({
solution: equation,
})
}
我想找到一些解决方案/函数,以便我能够输入带有变量的方程,然后选择一个变量,该函数将创建一个新方程,以便所选变量将位于方程的左侧其余的将在右侧。
求解给定变量的方程是一个非常复杂的问题。
您正在寻找的本质上是CAS对于 JavaScript。
如果您不介意在服务器上求解方程,您可以使用免费提供的 CAS 之一(单击here获取列表)
例如,在 MATLAB 中您可以使用solve(eq, var)求解特定变量。
就纯 javascript 实现而言,您可以使用coffeequate:
let equation = CQ("E = m*(c**2)");
let solutions = equation.solve("c");
for(let solution of solutions)
console.log("c =", solution.toString());
<script src="https://unpkg.com/[email protected]/coffeequate.min.js"></script>
但请注意coffeequate
不能解所有类型的方程。
你也可以摆脱你的eval
通过使用它toFunction:
let expression = CQ("a + b**c");
let fn = expression.toFunction("a", "b", "c");
console.log("1 + 2**3 =", fn(1, 2, 3).toString()); // 9
console.log("3 + 2**1 =", fn(3, 2, 1).toString()); // 5
<script src="https://unpkg.com/[email protected]/coffeequate.min.js"></script>
此外,您还可以用它来简化/扩展方程,如果您需要该功能:
let eqStr = "(x + y)*(x - y)";
let equation = CQ(eqStr);
console.log(eqStr, "===", equation.simplify().toString());
<script src="https://unpkg.com/[email protected]/coffeequate.min.js"></script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)