javascript - JS : Resolve a Formula for x

标签 javascript symbolic-math

我有一个包含多个组件的公式,例如 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/

相关文章:

javascript - 如何使用 JavaScript 删除加载 View 中的所有 Chrome 通知?

javascript - 415 不支持的媒体类型错误 - Domo 连接器

javascript - 根据时间和组对数组进行排序

math - 计算机代数系统简介?

z3 - 如何使用 z3 BitVec 或 Int 作为数组索引?

python - SymPy 中的非顺序替换

javascript - capture() 方法在 casperjs 中工作不正确

matlab - 警告:可能是虚假的解决方案。 [solvelib::checkSolutions]

matlab - 是否有 MATLAB 函数可以将符号表达式转换为 MATLAB 代码索引?

php - 使用 jquery 在父标签之外附加 html