JavaScript equation solver library
You can approximate the solution by doing what excel calls "Goal Seek" - testing values for x
until both sides of the equation approximately match. You can do this by splitting the equation by the "="
sign, replacing each occurence of x
with a value, eval
ing both sides, and determining if the difference falls below a certain threshold. While relatively simple, there are flaws to this method though (other than the fact that it is an approximation), for example the algorithm may think the two sides are converging when in fact it is just a local min/max and will diverge after the difference falls just below your threshold. You'll also need to test multiple start points to solve equations with more than one solution.
For a program to actually solve an equation as a human would (by rearranging the two sides of the equation and applying inverse functions, derivatives/integrals and whatnot) is far more complex, and somehow feels entirely proprietary ;)
I'd like to propose nerdamer. It can algebraically solve up to quartic functions and it can numerically solve a range of functions. Another library to consider is Algebrite.
//solve linear equations
var x = nerdamer.solve('(x+1)*3=x-6', 'x');
console.log(x.toString());
//quadratic
var x2 = nerdamer.solve('x^2-8x+15', 'x');
console.log(x2.toString());
//quadratic algebraically
var x3 = nerdamer.solve('x^2-ax+3*b', 'x');
console.log(x3.toString());
//multiple roots
var x4 = nerdamer.solve('x^6+41*x^5+652*x^4+5102*x^3+20581*x^2+40361*x+30030', 'x');
console.log(x4.toString());
//functions - numerically around to zero up to a predefined range
var x5 = nerdamer.solve('cos(x)^2+sin(x-1)', 'x');
console.log(x5.toString());
//solve a system of linear equations
var x6 = nerdamer.solveEquations(['2x+y=7', 'x-y+3z=11', 'y-z=-1']);
console.log(x6.toString());
//solve a system of nonlinear equations
var x7 = nerdamer.solveEquations(['3*x^2/y=2', 'z*x*y-1=35', '5*z^2+7=52']);
console.log(x7.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/Solve.js"></script>