Skip to content

Instantly share code, notes, and snippets.

@bwangelme
Last active September 2, 2016 03:30
Show Gist options
  • Save bwangelme/ad5d23014044e858748dcc56fbc81be4 to your computer and use it in GitHub Desktop.
Save bwangelme/ad5d23014044e858748dcc56fbc81be4 to your computer and use it in GitHub Desktop.
use python to solve the single-equation
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def solve(eq,var='x'):
"""利用Python来解一元方程。
代码来源:https://python-china.org/t/1152#
程序的思路就是把x当做了复数的虚部,然后利用虚部运算出x的系数
剩下的实数就是复数的实部,然后实部除以虚部,就得出x的解了。
"""
eq1 = eq.replace(" = "," - (")+")"
c = eval(eq1,{var:1j})
return -c.real/c.imag
print(solve("x - 2*x + 5*x - 46*(235-24) = x + 2"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment