I am looking into making an app for macOS written in Swift 3 that can solve equations. Specifically, I'd like to solve for a variable in an equation. For example, I want to input something like x + 5 = 10, and have 5 returned as the value of x. Is this natively possible in Swift, or is there an easy way to do this? Thanks in advance!
How Would You Solve For A Variable In An Equation?
You might want to wrap your math in swift via python...
See http://stackoverflow.com/questions/4449110/python-solve-equation-for-one-variable
You would need to write a parser to understand the equation :
either you let user write plain text as a * x + b = c
or provide a template to fill : [aField]. *. [x label.] + [b Field] = [c Field], where user would have to fill each field
at the end, you have to isolate a, b, c
Then the resolution is straightforward:
if a == 0, test if b == c : then any x is solution, otherwise, no solution
if a != 0, x = (c - b) / a
Once you have done this, you can extend the app with second order equation in the same way :
a * x² + b * x * c = 0
if a == 0, that's the previous case
if a != 0, then 2 cases :
if (b² - 4 a*c) >= 0, there are 2 values of x :
(-b + √(b² - 4 a*c)) / 2 * a and
(-b - √(b² - 4 a*c)) / 2 * a
if (b² - 4 a*c) < 0, there are 2 values of x, but imaginary numbers :
(-b + i √(-b² + 4 a*c)) / 2 * a and
(-b - i √(-b² + 4 a*c)) / 2 * a
Thanks. I'll definetly try this and let you know how it goes!
Have fun developing this.
Please note thjere was a typo in 2nd order equation :
should read:
a * x² + b * x + c = 0
instead of
a * x² + b * x * c = 0
Thanks! That's very helpful! Do you know how I might make a basic text parser that can extract the values of a, b, and c from one text field if written as something like this: a * x² + b * x + c = 0
Also, since I'm not quite as good at math as you are, I have to ask; does the above code solve for x in any instance with one instance of x?
For the parser, you should:
- search for = sign , to find the 2 members of equation
- then you can parse each member
- for the right, you get directly the value
- for the left member, first search for + sign to isolate each term
- then for each term, it will be easy to find the coefficients a, b, c.
For your second question
does the above code solve for x in any instance with one instance of x?
IN the first equqtion, you get x directly
FOr the second, you need to have x1 and x2 to hold the 2 solutions of the equqtion.