Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - เริ่มต้นใช้งาน SymPy สำหรับ Symbolic Mathematics

SymPy เป็นไลบรารี Python สำหรับ symbolic mathematics เป้าหมายเป็น Computer Algebra System (CAS) ที่ครบครัน โค้ดเรียบง่าย เข้าใจง่าย ขยายง่าย เขียนด้วย Python ทั้งหมด ขึ้นกับ mpmath สำหรับ arbitrary precision arithmetic

การติดตั้ง


pip install sympy

ชนิดตัวเลขใน SymPy

  • Rational: เศษส่วน เช่น Rational(1, 2) = 1/2, Rational(5, 2) = 5/2
  • Integer: จำนวนเต็ม

ตัวอย่างโค้ด


from sympy import *

# สัญลักษณ์คงที่พิเศษ
p = pi**3
print("value of p is :", str(p))  # pi**3 (symbolic)

# evalf() ประเมินเป็น floating-point
q = pi.evalf()
print("value of q is :", str(q))  # 3.14159265358979

r = exp(1).evalf()
print("value of r is :", str(r))  # 2.71828182845905

s = (pi + exp(1)).evalf()
print("value of s is :", str(s))  # 5.85987448204884

# Infinity
rslt = oo + 10000
print("value of rslt is :", str(rslt))  # oo

if oo > 9999999:
    print("True")
else:
    print("False")

ผลลัพธ์


value of p is : pi**3
value of q is : 3.14159265358979
value of r is : 2.71828182845905
value of s is : 5.85987448204884
value of rslt is : oo
True

ความสามารถหลักของ SymPy

1. Symbolic Variables และ Expressions


from sympy import symbols, expand, factor, simplify

x, y = symbols('x y')
expr = (x + y)**2
print(expand(expr))    # x**2 + 2*x*y + y**2
print(factor(x**2 - y**2))  # (x - y)*(x + y)
print(simplify(sin(x)**2 + cos(x)**2))  # 1

2. Calculus: Differentiation & Integration


from sympy import diff, integrate, limit, oo

x = symbols('x')
f = x**3 + 2*x**2 + x + 1

# Differentiation
print(diff(f, x))           # 3*x**2 + 4*x + 1
print(diff(f, x, 2))        # 6*x + 4 (second derivative)

# Integration
print(integrate(f, x))      # x**4/4 + 2*x**3/3 + x**2/2 + x
print(integrate(f, (x, 0, 1)))  # Definite integral: 25/12

# Limit
print(limit(sin(x)/x, x, 0))  # 1
print(limit(1/x, x, oo))      # 0

3. Solving Equations


from sympy import solve, Eq

x, y = symbols('x y')
eq1 = Eq(x + y, 10)
eq2 = Eq(x - y, 2)
sol = solve((eq1, eq2), (x, y))
print(sol)  # {x: 6, y: 4}

# Polynomial roots
print(solve(x**2 - 5*x + 6, x))  # [2, 3]

4. Series Expansion


from sympy import series
print(series(sin(x), x, 0, 6))  # x - x**3/6 + x**5/120 + O(x**6)

5. Matrices


from sympy import Matrix
M = Matrix([[1, 2], [3, 4]])
print(M.det())        # -2
print(M.inv())        # Inverse
print(M.eigenvals())  # Eigenvalues

สรุป

  • SymPy ทำ symbolic math ได้: algebra, calculus, solving, matrices
  • ใช้ symbols() สร้างตัวแปรสัญลักษณ์
  • ใช้ evalf() หรือ N() แปลงเป็น numeric
  • คงค่าความแม่นยำได้ (ไม่สูญเสีย precision)
  • เหมาะสำหรับ: การพิสูจน์คณิตศาสตร์, สูตรอัลจิบรา, calculus, physics simulations