【发布时间】:2018-07-22 09:37:17
【问题描述】:
我有类型的方程
23/(x+3) +[ (x-3)/(x+3) ] *2 = 57
我想用 java-script 求解 x。是否有任何 javascript 库可以求解这些类型的方程。谢谢你的帮助。
【问题讨论】:
-
你的方程实际上是你需要解析的字符串,还是只需要在开发过程中在 JavaScript 中计算?
标签: javascript
我有类型的方程
23/(x+3) +[ (x-3)/(x+3) ] *2 = 57
我想用 java-script 求解 x。是否有任何 javascript 库可以求解这些类型的方程。谢谢你的帮助。
【问题讨论】:
标签: javascript
您可以使用这个库algebra.js,但您需要为表达式编写解析器,您可以为此使用Peg.JS 或自己编写解析器。只有少量的令牌应该不会那么难。
【讨论】:
您可以使用这个expression evaluator - 它允许您将表达式传递给解析器,该解析器返回一个函数对象,该函数对象可以评估您给它的输入。
这是一个例子:
var expr = Parser.parse("2 ^ x");
expr.evaluate({ x: 3 }); // 8
【讨论】:
有一些 JavaScript 求解器可以用数字方式解决您的问题。我知道的非线性求解器是Ceres.js。这是一个适合您的问题的示例。我们要做的第一件事是重新排列为 F(x)=0 的形式。
x0 = -2.7999999997597933
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h2>User Function</h2>
<p>This is an example of the solution of a user supplied function using Ceres.js</p>
<textarea id="demo" rows="40" cols="170">
</textarea>
<script type="module">
import {Ceres} from 'https://cdn.jsdelivr.net/gh/Pterodactylus/Ceres.js@master/Ceres-v1.5.3.js'
var fn1 = function f1(x){
//You have to rearrange your function to equal zero 23/(x[0]+3)+((x[0]-3)/(x[0]+3))*2=57
return 23/(x[0]+3)+((x[0]-3)/(x[0]+3))*2-57;
}
let solver = new Ceres()
solver.add_function(fn1) //Add the first equation to the solver.
solver.promise.then(function(result) {
var x_guess = [1] //Guess the initial values of the solution.
var s = solver.solve(x_guess) //Solve the equation
var x = s.x //assign the calculated solution array to the variable x
document.getElementById("demo").value = s.report //Print solver report
solver.remove() //required to free the memory in C++
})
</script>
</body>
</html>
【讨论】: