This article brings you an introduction to the techniques of solving equations in Python (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
numpy is a bit complicated to use to solve equations, and you need to use matrix thinking! I didn't learn matrices well and numpy can't solve nonlinear equations, so... I don't know how to do this either!
It is inferior to sage and z3, but it is also very good at solving equations!
from sympy import * x = symbols('x') y = symbols('y') res = solve([x+y-3,x-y-1],[x,y])[0] print(res)
sage can solve both linear and nonlinear equations. It can be called an artifact in the world of equation solving. However, expressions do not support bit operations, such as: AND or Not, remainder and XOR. Equations where bit operations occur can only be solved using z3 to create constraints! The advantages of sage are also obvious: expressions are simple and easy to write, and calculation speed is fast!
Online sage solver
var('x y') solve([x**3+y**2+666==142335262,x**2-y==269086,x+y==1834],[x,y])
z3 is also called a constraint solver and can be used to solve any equation without any problem! But windows is not easy to install, so I basically run it on linux
, both python2 and python3 are supported! The idea of using it is very simple:
First create a symbolic variable of the type you need
Then initialize a constraint,
Add constraints
Finally determine whether the constraints have solutions and solve for variables
The commonly used functions are listed below. Az3-solver document
# 符号变量类型 Int('x') Real('x') Bool('x') BitVec('x',N) # N bit的符号变量,用于位操作 BitVecVal(num,N) # N bit的数据 num # 初始化约束器 solver = Solver() # 添加约束 solver.add(x+y==10,x-y==0) # 求解约束 solver.check() ans = solver.mode() # 初始化多个符号变量 x = [Int('x%d' % i) for i in range(n)] # 取结果中某个变量的值 value = ans[x].as_long()
The above is the detailed content of Introduction to techniques for solving equations in Python (code examples). For more information, please follow other related articles on the PHP Chinese website!