程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Linear algebra solution -- python model

編輯:Python

線性代數模型

  • 差分方程模型
    • 1.斐波那契(Fibonacci)數列的通項

差分方程模型

1.斐波那契(Fibonacci)數列的通項

Fibonacci is here13世紀提出,A pair of rabbits starts breeding a month after birth,A pair of newborn rabbits are born every month
,It is assumed that rabbits only breed,沒有死亡,問第kHow many pairs of rabbits will there be in the month of birth:

解:
in pairs,The number of pairs of rabbits bred each month forms a series,This is the famous Fibonacci sequence,
1 , 1 , 2 , 3 , 5 , 8... 1,1,2,3,5,8... 1,1,2,3,5,8...,,this book F k F_k Fk​,滿足條件:
F 0 = 1 , F 1 = 1 , F k + 2 = F k + 1 + F k F_0=1,F_1=1,F_{k+2}=F_{k+1}+F_k F0​=1,F1​=1,Fk+2​=Fk+1​+Fk​
**解法1:**The eigenroot solution of difference equations
The characteristic roots of the difference equation are :
λ 2 − λ − 1 = 0 \lambda^2-\lambda-1=0 λ2−λ−1=0
特征根 λ 1 = \lambda_1= λ1​= 1 − 5 2 , λ 2 = \frac{1-\sqrt{5}}{2},\lambda_2= 21−5​​,λ2​= 1 + 5 2 \frac{1+\sqrt{5}}{2} 21+5​​是互異的.所以通解為:
F k = c 1 ( 1 − 5 2 ) k + c 2 ( 1 + 5 2 ) k F_k=c_1\left( \frac{1-\sqrt{5}}{2} \right) ^k+c_2\left( \frac{1+\sqrt{5}}{2} \right) ^k Fk​=c1​(21−5​​)k+c2​(21+5​​)k
Use initial value conditions: F 0 = 1 , F 1 = 1 F_0=1,F_1=1 F0​=1,F1​=1,得到方程組:

{ c 1 + c 2 = 1 c 1 ( 1 − 5 2 ) + c 2 ( 1 + 5 2 ) = 1 \begin{cases} c_1+c_2=1\\ c_1\left( \frac{1-\sqrt{5}}{2} \right) +c_2\left( \frac{1+\sqrt{5}}{2} \right) =1\\ \end{cases} { c1​+c2​=1c1​(21−5​​)+c2​(21+5​​)=1​

解得: c 1 = 1 2 − 5 10 , c 2 = 1 2 + 5 10 c_1=\frac{1}{2}-\frac{\sqrt{5}}{10},c_2=\frac{1}{2}+\frac{\sqrt{5}}{10} c1​=21​−105​​,c2​=21​+105​​
於是:初值問題的解為:

F k = ( 1 2 − 5 10 ) ( 1 − 5 2 ) k + ( 1 2 + 5 10 ) ( 1 + 5 2 ) k F_k=\left( \frac{1}{2}-\frac{\sqrt{5}}{10} \right) \left( \frac{1-\sqrt{5}}{2} \right) ^k+\left( \frac{1}{2}+\frac{\sqrt{5}}{10} \right) \left( \frac{1+\sqrt{5}}{2} \right) ^k Fk​=(21​−105​​)(21−5​​)k+(21​+105​​)(21+5​​)k
代碼:

import sympy as sp
sp.var("t,c1,c2")
t0=sp.solve(t**2-t-1)#Solve the eigenroot equation,
eq1=c1+c2-1
eq2=c1*t0[0]+c2*t0[1]-1
s=sp.solve([eq1,eq2])#求解線性方程組
print("c1=",s[c1],"\n""c2=",s[c2])#Output the solution of the linear system of equations
print("初值問題的解為:""\n",s[c1]*t0[0]+s[c2]*t0[1])#Output the solution to the initial problem


解法二:直接利用python軟件求解

import sympy as sp
sp.var("k")
y=sp.Function("y")
f=y(k+2)-y(k+1)-y(k)
s=sp.rsolve(f,y(k),{
y(0):1,y(1):1})#注意這裡是rsolve
print(s)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved