我有一个包含多个组件的公式,例如 w = x * y/z^2 + c
。现在我为每个变量都有一个输入字段。我的目标是,在输入所有其他项后,尽快计算出缺失的项。困难在于,您可以选择填写哪些字段以及想要保留哪些字段。
简单(天真的)方法当然是手动解析每个变量,检测丢失的 var,并为每种情况提供单独的 js 函数。但我什至还有链接公式(例如上面公式中的 x 也是 x = a + b),并且选项几乎都是不定式。 JS 中有没有选项可以通过指定变量求解公式?然后,我可以用分配的值替换每个变量字符串,然后eval
该字符串。
首先我想到Nerdamer本来就是这样,但事实证明它只能计算表达式而不能处理方程。
这可能吗?还有更好的主意吗?
提前致谢!
P.S.:我的实际公式是:
dR = c * I^2 / A
R = L * dR
P = I * U
DV = R * I
DW = DV * I
用于计算由于欧姆电阻引起的电缆损耗。每个变量都有一个相应的输入字段。
最佳答案
可以使用 nerdamer 构建以下解决方案来查找“R” 。可以扩展该逻辑来求解剩余变量。请记住,当前的限制是 nerdamer 目前只能以代数方式求解三次函数。高阶函数将通过数值求解。
//You can then take care of the non linear containing I. I is quadratic
var dR = nerdamer('R=L*dR').solveFor('dR');
var I = nerdamer('dR=c*I^2/A').sub('dR', dR).solveFor('I');
//You can first start by reducing the first few equations since they are linear and you can solve them as a linear system
var solutions = nerdamer.solveEquations(['P = I * U', 'DV = R * I', 'DW = DV * I'], ['I', 'DW', 'P']);
//the solutions come back as an array arrays in the form of [variable, value]
//you can see what they look like. In your case all your solutions will be in terns of DV & U since these are the only actual knowns
//You can see what the solutions look like
solutions.map(function(x) {
console.log('-'+x[0]+' = '+x[1]);
});
console.log('------------------ R ----------------');
var R = nerdamer.setEquation(I[0], solutions[0][1]).solveFor('R');
//I will have 3 solutions since it's cubic. You can console.log them below
R.map(function(x) {
console.log('R = '+x.toString());
});
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/nerdamer.core.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Algebra.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Calculus.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Extra.js"></script>
<script src="https://cdn.jsdelivr.net/npm/nerdamer@latest/Solve.js"></script>
关于javascript - JS : Resolve a Formula for x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27103639/