-1

I have equation of type

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

I want to solve for x with java-script.Is there any javascript library to solve these type of equations.Thank you for your help.

Alex
  • 9
  • 4
  • Is your equation actually a string you need to parse, or do you just need to calculate this in JavaScript during development? – ssc-hrep3 Jul 22 '18 at 09:39

3 Answers3

1

You can use this library algebra.js but you will need to write a Parser for expressions, you can use Peg.JS for this or write the parser yourself. With only handful of tokens it should not be that hard.

jcubic
  • 61,973
  • 54
  • 229
  • 402
1

You can use this expression evaluator - it allows you to pass expressions into a parser that returns a function object that can evaluate the input you are given it.

Here's an example:

var expr = Parser.parse("2 ^ x");
expr.evaluate({ x: 3 }); // 8
martinsoender
  • 213
  • 1
  • 9
0

There are JavaScript solvers out there that will numerically solve your problem. The non-linear solver that I know of is Ceres.js. Here is an example adapted to your question. The first thing we have to do is rearrange to the form 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>