04-sympy代数和解方程

解方程

解一元方程

1
solve(x**2-3*x+2, x)

解二元方程

1
solve([x+5*y-2, -3*x+6*y-15], [x, y])

代数运算

1
2
expr = x**2 + 2*x + 1
expr
  • 令x=2
1
expr.subs(x, 2)
  • 令x = y+1
1
expr.subs(x, y+1)
  • 求n的阶乘
1
2
3
4
n, k = symbols('n, k', integer=True)
a = factorial(n)
a
a.subs(n, 3)
  • 多元函数的代数
1
2
3
expr = x**3 + 4*x*y - z
expr
expr.subs([(x, 2), (y, 4), (z, 0)])

字符串转sympy表达式

1
2
3
4
str_expr = "x**2 + 3*x - 1/2"
expr = sympify(str_expr)  # Not to be confused with simplify
expr
expr.subs(x,1)