%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
1/2 + 1/3
0.8333333333333333
可不可以加出 5/6 呢?
from sympy import *
Rational(1,2) + Rational(1,3)
S(1)/2 + S(1)/3
5/6
美化輸出
init_printing()
設一個變數。
x = symbols('x')
設兩個變數可以用:
x, y = symbols('x y')
f = x**3 + 2*x**2 - 5
f
diff(f)
integrate(f)
順便畫個圖。
plot(f)
<sympy.plotting.plot.Plot at 0x10c5ce048>
第二種設變數的方式。
from sympy.abc import a, b, c
和剛剛有點不同, 我們指定變數
f = a*x**2 + b*x + c
diff(f,x)
diff(sin(x), x)
diff(ln(x), x)
integrate(f,x)
設範圍
integrate(1/x, (x, 1, 3))
integrate(exp(x),x)
無窮大符號: oo
integrate(exp(-x**2), (x, -oo, oo))
limit(sin(x)/x, x, 0)
limit(sin(a*x)/x, x, 0)
solve(x**2 + x + 1, x)
我們再加一個 y
y = symbols('y')
聯立方程組假設式子都是等於零。
solve([x - 2*y + 5, x + y -4], [x,y])
solve([a*x - 2*y + 5, x + y -4], [x,y])
A = Matrix([[1,2],[3,4]])
B = np.matrix([[1,2],[3,4]])
A[0,1]
B[0,1]
2
A.row(0)
B[0]
matrix([[1, 2]])
A.col(1)
B[:,1]
matrix([[2], [4]])
reduced row echelon form 這樣做。第二項資料是 pivot 行。
A.rref()
A.inv()
B**(-1)
matrix([[-2. , 1. ], [ 1.5, -0.5]])
A.transpose()
A.T
A.det()
A.eigenvals()
符號也可以的。
v = Matrix([[x,y]]).T
# v = Matrix([[x],[y]])
A*v
我們來解 $$y'' + y =0$$ 這個微分方程式。聽說解是長這樣:
$$A \sin(x) + B \cos(x)$$首先, 我們先來告訴 SymPy, f 是個函數。
f = symbols('f', cls=Function)
f(x).diff(x)
f(x).diff(x,x)
dsolve(f(x).diff(x,x)+f(x), f(x))
eq = (x+1)**2
eq
eq.subs(x, (a+b))
eq.subs(x, 3)
eq.subs(x,pi)
之前我們簡單畫過一個圖, 我們再深入研究一點。
plot(sin(x))
<sympy.plotting.plot.Plot at 0x10fd38160>
限制範圍。
plot(sin(x), (x, -2*pi, 2*pi))
<sympy.plotting.plot.Plot at 0x110012550>
多個函數一起來。
plot(sin(x), cos(x), (x,-2*pi,2*pi))
<sympy.plotting.plot.Plot at 0x1104f42e8>
from sympy.plotting import plot_parametric
from sympy.abc import t
r = 1 + 0.3*sin(10*t)
plot_parametric(r*cos(t), r*sin(t), (t,0,2*pi))
<sympy.plotting.plot.Plot at 0x111489be0>
plot_implicit(Eq(x**2+y**2,3))
<sympy.plotting.plot.Plot at 0x1105e20b8>
也可以畫不等式。
plot_implicit(y>x**2)
<sympy.plotting.plot.Plot at 0x1115585f8>
from IPython.display import display
def quiz():
c1 = np.random.randint(1,6)
c2 = np.random.randint(1,6)
c3 = np.random.randint(1,6)
f = c1*x**2 + c2*x + c3
display(f)
w = input("按 enter 告訴你答案...")
g = integrate(f,x)
display(g)
quiz()
按 enter 告訴你答案...
f = coef[0]*x**2 + coef[1]*x + coef[2]
s = str(pi.n(100000))
s.find('1215')
s[11940:11950]
'1712158552'
cutepi = str(pi.n(200))
cutepi.find('822')
數學很喜歡的希臘字母當符號...
delta = symbols('delta')
(delta - 1)**2
比較特別是 lambda, 因為 lambda 是 Python 保留字, 我們只好假裝不會拼 lambda。
lamda = symbols('lamda')p = M.charpoly(lamda)v
M = Matrix([[0,1,0],[2,0,1],[0,-1,0]])
p = M.charpoly(lamda)
factor(p)