sympy —— Python 符號運算

Inside_Zhang發表於2015-11-22

0. 素因子分解

>> import sympy
>> from sympy.ntheory import factorint
>> factorint(100)
{2: 1, 3: 1, 5: 2}

1. sympy:Python 自帶符號運算庫

  1. from sympy import *

  2. 自帶常量E和複數單位I

  3. 簡單測試

>>>x = Symbol('x', real=True)
>>>y = Symbol('y', real=True) 
>>>(x+y)**2
(x + y)**2
>>>expand((x+y)**2, real=True)
x**2 + 2*x*y + y**2

比如我們使用 sympy 來驗證如下的等式:

x2+y2=(x+(2xy)1/2+y)(x(2xy)1/2+y)
\begin{split} x^2+y^2=&(x+(2xy)^{1/2}+y)(x-(2xy)^{1/2}+y)\\ \end{split}
>> from sympy import Symbol, expand
>> from fractions import Fraction

>> x = Symbol('x')
>> y = Symbol('y')
>> expand((x+(2*x*y)**Fraction(1, 2)+y)*(x-(2*x*y)**Fraction(1, 2)+y))
x**2 + y**2

該等式的簡單證明如下:

x2+y2==(x+y)22xy(x+y+2xy)(x+y2xy)
\begin{split} x^2+y^2=&\left(x+y\right)^2-2xy\\ =&\left(x+y+\sqrt{2xy}\right)\left(x+y-\sqrt{2xy}\right) \end{split}

2. sympy:多項式運算

x(x2+x1)2
x\cdot \left(x^2+x-1\right)^2
>> from sympy import poly
>> from sympy.abc import x
>> poly(x*(x**2+x-1)**2)
Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ')

Polynomials Manipulation Module Reference

3. 解方程

使用 Python 解數學方程

  • 解一元一次方程:3x6=0

    3x-6=0

    >> from sympy import Symbol, solve
    >> x = Symbol('x')
    >> solve(x*3-6, x)
    [2]
  • 解 二元一次方程組:

    {y=1x3x+2y=5
    \left\{ \begin{split} y=1-x\\ 3x+2y=5 \end{split} \right.
    >> x = Symbol('x')
    >> y = Symbol('y')
    >> f1 = y+x-1
    >> f2 = 3*x+2*y-5
    >> solve([f1, f2], [x, y])
    {x: 3, y: -2}

4. python 模擬

class array(object):
    def __init__(self, value, name=None):
        self.value = value
        if name:
            self.grad = lambda g: {name : g}
            # 定義梯度函式,返回一個字典

    # '+' 加號運算子過載
    def __add__(self, other):
        assert isinstance(other, int)
        ret = array(self.value+other)
        ret.grad = self.grad
        return ret

    # '*' 乘法運算子過載
    def __mul__(self, other):
        assert isinstance(other, array)
        ret = array(self.value*other.value)
        def grad(g):
            x = self.grad(g*other.value)
            x.update(other.grad(self.value*g))
                #  也即x*y,對x(self)的導數等於y(other),反之亦然
            return x
        ret.grad = grad
        return ret
x = array(1, 'x')
y = array(2, 'y')
w = x*y
z = w + 1
print(z.value)
print(z.grad(1))
            # z.grad是成員函式,而不是一個變數,或者一個字典

相關文章