This is a project I made in 11th grade, before I knew anything about data structures. After taking a Data Structures class, I realized thatTrees
and Stacks
are actual things and that this idea of converting mathematical expressions into trees is not a new idea lol. Still was a cool project at the time.
Edit: After taking Intro to Systems Software and learning more about compilers, I thought of this project and realized in a way it is sort of a compiler.
A Github-Pages link was made to show this off (it includes cool visuals as well). Check out the gh-pages
branch, or click this link
Grab the deriver.js file from dist
folder to get the latest version.
Deriver.derive("3x^2+3") // 6x
Deriver.derive("tan2x+sinx") // 2sec(2x)^2+cosx
An input is given as a string. This string is "cleaned", which inserts multiplication symbols where neccesary. For example, 2*x is usually written by 2x. And sin(2*x) is usually written as sin(2x). The cleaned input is parsed into a Tree. The root of a tree is a value. The root of the parsed tree in this example is a '+' operator. The left and right branches of a tree are also Trees. Computers are much better at understanding trees than understanding strings. This makes manipulation a lot easier. This tree is then derived. All of the derivative rules are programmed in, and the derive method follows them. The result is a tree, which is then simplified and then unparsed from a tree back to a string!
To view the individual functions
I recommend reading through the docs in this order though:
- How to manage parentheses
- Many different rules for derivatives
- How to teach different between negative and subtraction
- Trig?!?!
- Best way to do all the string manipulation (which was actually to do no string manipulation)
- How to handle omission of multiplication signs
I tried documenting this project thoroughly to allow others interested in CS to experience the same fascination in solving the issue of parsing expressions.