-2

I want to allow users to input a mathematical equation. The equations will be simple but there will be some unknown variables.

Example 1: x + y - 10 here we have x and y unknown.

Example 2: (a + b) * (c + d) here we have a, b, c, and d unknown.

Note that the user can input n number of variables in the equation.

Now, I want to find those unknown variables from the equation. And later I will prompt the user to provide the values for those unknown variables.

Subhojit Ghosh
  • 257
  • 3
  • 10
  • 1
    This is a simple algebra, you have two variables and one equation, how would you do that? – Manish Kumar Aug 15 '21 at 17:15
  • Actually, I have to take input from the user for those variables. So that I can solve the equation and return a value. That's why I need to extract unknown variables. – Subhojit Ghosh Aug 15 '21 at 17:18
  • ok , can't you use simple function to return the result, for your use case :- function evaluate(a, b) { return a + b - 1 } – Manish Kumar Aug 15 '21 at 17:25
  • variables are not just two and the number of variables is not also limited. Users can input a formula that has n number of variables. – Subhojit Ghosh Aug 15 '21 at 17:26
  • That's a more convoluted requirement, please elaborate this here so that community can understand your requirement in detail. what can a equation be etc. – Manish Kumar Aug 15 '21 at 17:31
  • Hi, @ManishSoni I have edited my question with more details. – Subhojit Ghosh Aug 15 '21 at 17:52

2 Answers2

1

The Math.js library does not have support equations and only supports one-sided expressions. So you would not be able to solve for x using Math.js. See this post for equation solving libraries.

SciDev
  • 159
  • 6
1

Math.js provides an Expression Tree API where you can filter the expression using math.parse(expr) and return the 'unknowns' you are looking for:

let expr1 = 'x + y - 10'
let expr2 = '(a + b) * (c + d)'

const node1 = math.parse(expr1).filter(node => node.isSymbolNode)
const node2 = math.parse(expr2).filter(node => node.isSymbolNode)

var result1 = [...new Set(node1.map(item => item.name))]
var result2 = [...new Set(node2.map(item => item.name))]

console.log(result1)
console.log(result2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.4/math.min.js"></script>
Timur
  • 1,682
  • 1
  • 4
  • 11