如何用JavaScript求解复杂的方程



我有类型的方程

23/(x+3)  +[ (x-3)/(x+3) ] *2 = 57

我想用java脚本求解x。有没有javascript库可以解决这些类型的方程。谢谢你的帮助。

您可以使用这个库algebra.js,但您需要为表达式编写Parser,您可以使用Peg。JS,或者自己编写解析器。只有少量代币,应该不会那么难。

您可以使用此表达式计算器-它允许您将表达式传递到一个解析器中,该解析器返回一个函数对象,该对象可以对给定的输入进行评估。

这里有一个例子:

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>

最新更新