Python implements three lines of code to solve simple unitary equations

  • 2020-04-02 13:59:11
  • OfStack

The example described in this paper USES 3 lines of code for Python to realize the solution of unitary equation, which is simple and efficient. The specific usage is as follows:


>>> solve("x - 2*x + 5*x - 46*(235-24) = x + 2")
3236.0

The functional code is as follows:


def solve(eq,var='x'):
  eq1 = eq.replace("=","-(")+")"
  c = eval(eq1,{var:1j})
  return -c.real/c.imag

Let's read the code.

The first is the first row, which distorts the equation to produce a 0 formula "x minus 2 times x plus 5 times x minus 46 times (235-24) minus x plus 2".
The second line USES eval to execute this expression, and we substitute x = 1j into the expression, which is -9708+3j.
And notice that x is equal to 1j, so this equation simplifies to minus 9708 plus 3x is equal to 0, so you just take minus 9708 over 3 and you get x.
And -9708 is the real part of this complex number, and 3 is the imaginary part of this complex number, so the result becomes -c.eal/c.img.
So obviously, this function cannot solve complex Numbers.
By the way, Python 2.x's/operation USES integer division, resulting in lost decimals, so Python 3.x should be used to get the right result.

Hopefully, the examples described in this article will help you learn Python.


Related articles: