Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Representing Math Equations as Java Objects

Tags:

java

math

I am trying to design a way to represent mathematical equations as Java Objects. This is what I've come up with so far:

  • Term
  • -Includes fields such as coefficient (which could be negative), exponent and variable (x, y, z, etc). Some fields may even qualify as their own terms alltogether, introducing recursion.
  • -Objects that extend Term would include things such as TrigTerm to represent trigonometric functions.

  • Equation

  • -This is a collection of Terms
  • -The toString() method of Equation would call the toString() method of all of its Terms and concatenate the results.

The overall idea is that I would be able to programmatically manipulate the equations (for example, a dirivative method that would return an equation that is the derivative of the equation it was called for, or an evaluate method that would evaluate an equation for a certain variable equaling a certain value).


What I have works fine for simple equations:
x^2 + 3
This is just two Terms: one with a variable "x" and an exponent "2" and another which is just a constant "3."


But not so much for more complex equations:
alt text
Yes, this is a terrible example but I'm just making a point.


So now for the question: what would be the best way to represent math equations as Java objects? Are there any libraries that already do this?

like image 812
knpwrs Avatar asked Dec 07 '22 01:12

knpwrs


1 Answers

what would be the best way to represent math equations as Java objects?

I want you to notice, you don't have any equations. Equations look like this;

x = 3

What you have are expressions: collections of symbols that could, under some circumstances, evaluate out to some particular values.

You should write a class Expression. Expression has three subclasses: Constant (e.g. 3), Variable (e.g. x), and Operation.

An Operation has a type (e.g. "exponentiation" or "negation") and a list of Expressions to work on. That's the key idea: an Operation, which is an Expression, also has some number of Expressions.

So your is SUM(EXP(X, 2), 3) -- that is, the SUM Operation, taking two expressions, the first being the Exponentiation of the Expressions Variable X and Constant 2, and the second being the Constant 3.

This concept can be infinitely elaborated to represent any expression you can write on paper.

The hard part is evaluating a string that represents your expression and producing an Expression object -- as someone suggested, read some papers about parsing. It's the hardest part but still pretty easy.

Evaluating an Expression (given fixed values for all your Variables) and printing one out are actually quite easy. More complicated transforms (like differentiation and integration) can be challenging but are still not rocket science.

like image 182
Michael Lorton Avatar answered Dec 09 '22 13:12

Michael Lorton