├── .vscode └── settings.json ├── eight ├── Quadratic_spline_interpolation.py ├── cubic_spline_interpolation.py └── readme.md ├── first ├── bijin.py └── taile.py ├── five ├── Regression.py └── readme.md ├── four ├── beer.png ├── beer.py └── readme.md ├── nine └── Gaussian_elimination.py ├── readme.md ├── second ├── erfen.py └── shiwei.py ├── senve └── lglr.py ├── six └── Newton.py ├── ten └── LU.py └── third ├── readme.md └── 开放法.py /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.linting.pylintEnabled": false 3 | } -------------------------------------------------------------------------------- /eight/Quadratic_spline_interpolation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Nov 12 15:00:11 2017 4 | 5 | @author: 大帆 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | N=4 12 | x=np.array([3,4.5,7,9]) 13 | 14 | #y=1/(1+np.exp(-x)) 15 | y=np.array([2.5,1,2.5,0.5]) 16 | 17 | f=plt.figure() 18 | plt.plot(x,y) 19 | plt.show() 20 | 21 | 22 | X=np.zeros([3*(N-1)-1,3*(N-1)]) 23 | Y=np.zeros([3*(N-1)-1,1]) 24 | 25 | j=0 26 | for i in range(N-2): 27 | # print(y[i+1]) 28 | # print(x[i+1]) 29 | Y[2*i]=y[i+1] 30 | Y[i*2+1]=y[i+1] 31 | for _ in range(2): 32 | X[2*i+_,3*j]=x[i+1]**2 33 | X[2*i+_,3*j+1]=x[i+1] 34 | X[2*i+_,3*j+2]=1 35 | if _ ==0: 36 | j=(j+1)%(N-1) 37 | pass 38 | 39 | j=2*(N-1)-2 40 | X[j,0]=x[0]**2 41 | X[j,1]=x[0] 42 | X[j,2]=1 43 | Y[j]=y[0] 44 | 45 | X[j+1,-3]=x[-1]**2 46 | X[j+1,-2]=x[-1] 47 | X[j+1,-1]=1 48 | Y[j+1]=y[-1] 49 | 50 | h=2*(N-1) 51 | j=0 52 | 53 | for i in range(N-2): 54 | X[i+h,3*j+0]=x[i+1]*2 55 | X[i+h,3*j+1]=1 56 | X[i+h,3*j+2]=0 57 | X[i+h,3*j+3]=-x[i+1]*2 58 | X[i+h,3*j+4]=-1 59 | j+=1 60 | 61 | X=np.mat(X[:,1:]) 62 | Y=np.mat(Y) 63 | 64 | a0=0 65 | w=X.I*Y 66 | 67 | def pre(xx): 68 | for i in range(N-1): 69 | if x[i]<=xx and xx<=x[i+1]: 70 | if i==0: 71 | return a0*xx**2+w[0]*xx+w[1] 72 | 73 | else: 74 | return w[i*3-1]*xx**2+w[i*3]*xx+w[i*3+1] 75 | 76 | break 77 | else: 78 | pass 79 | 80 | xx=np.arange(3,9,0.2) 81 | yy=np.apply_along_axis(pre,1,xx) -------------------------------------------------------------------------------- /eight/cubic_spline_interpolation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sun Nov 12 15:00:11 2017 4 | 5 | @author: 大帆 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | plt.rcParams['font.sans-serif'] = ['SimHei'] 11 | plt.rcParams['font.family']='sans-serif' 12 | plt.rcParams['axes.unicode_minus'] = False 13 | 14 | 15 | def cubic_spline_interpolation(x,y): 16 | N=len(x) 17 | X=np.zeros([4*(N-1)-2,4*(N-1)]) 18 | Y=np.zeros([4*(N-1)-2,1]) 19 | j=0 20 | for i in range(N-2): 21 | # print(y[i+1]) 22 | # print(x[i+1]) 23 | Y[2*i]=y[i+1] 24 | Y[i*2+1]=y[i+1] 25 | for _ in range(2): 26 | X[2*i+_,4*j]=x[i+1]**3 27 | X[2*i+_,4*j+1]=x[i+1]**2 28 | X[2*i+_,4*j+2]=x[i+1] 29 | X[2*i+_,4*j+3]=1 30 | if _ ==0: 31 | j=(j+1)%(N-1) 32 | pass 33 | 34 | j=2*(N-1)-2 35 | X[j,0]=x[0]**3 36 | X[j,1]=x[0]**2 37 | X[j,2]=x[0] 38 | X[j,3]=1 39 | Y[j]=y[0] 40 | 41 | X[j+1,-4]=x[-1]**3 42 | X[j+1,-3]=x[-1]**2 43 | X[j+1,-2]=x[-1] 44 | X[j+1,-1]=1 45 | Y[j+1]=y[-1] 46 | 47 | h=2*(N-1) 48 | j=0 49 | 50 | for i in range(N-2): 51 | X[i+h,4*j+0]=x[i+1]**2*3 52 | X[i+h,4*j+1]= x[i+1]*2 53 | X[i+h,4*j+2]= 1 54 | X[i+h,4*j+3]= 0 55 | X[i+h,4*j+4]=-x[i+1]**2*3 56 | X[i+h,4*j+5]= -x[i+1]*2 57 | X[i+h,4*j+6]= -1 58 | j+=1 59 | 60 | j=0 61 | h=2*(N-1)+N-2 62 | for i in range(N-2): 63 | X[i+h,4*j+0]=6*x[i+1] 64 | X[i+h,4*j+1]=2 65 | X[i+h,4*j+4]=-6*x[i+1] 66 | X[i+h,4*j+5]=-2 67 | j+=1 68 | 69 | 70 | X=np.mat(np.c_[X[:,1:-4],X[:,-3:]]) 71 | 72 | Y=np.mat(Y) 73 | a0=0 74 | w=X.I*Y 75 | an=0 76 | def pre(xx): 77 | for i in range(N-1): 78 | if x[i]<=xx and xx-x[i+1]<=0.001: 79 | if i==0: 80 | return a0*xx**3+w[0]*xx**2+w[1]*xx+w[2] 81 | elif i==N-2: 82 | return an*xx**3+w[-3]*xx**2+w[-2]*xx+w[-1] 83 | else: 84 | return w[i*4-1]*xx**3+w[i*4]*xx**2+w[i*4+1]*xx+w[i*4+2] 85 | 86 | break 87 | else: 88 | pass 89 | def res(x): 90 | if type(x)==int: 91 | return pre(x) 92 | else: 93 | x=np.array(x) 94 | return np.apply_along_axis(pre,1,x.reshape([-1,1])) 95 | return res 96 | 97 | x=np.array([3,4.5,7,9]) 98 | y=np.array([2.5,1,2.5,0.5]) 99 | f=plt.figure() 100 | one=plt.plot(x,y) 101 | xx=np.arange(3,9.1,0.2) 102 | #调用三次样条函数 103 | yy=cubic_spline_interpolation(x,y)(xx) 104 | three=plt.plot(xx,yy) 105 | plt.legend(one+three,['线性样条','三次样条']) 106 | plt.show() 107 | 108 | 109 | x=np.arange(10)-5 110 | y=1/(1+np.exp(-x)) 111 | xx=np.arange(x.min(),x.max()+0.1,0.2) 112 | #调用三次样条函数 113 | yy=cubic_spline_interpolation(x,y)(xx) 114 | f=plt.figure() 115 | one=plt.plot(x,y) 116 | three=plt.plot(xx,yy) 117 | plt.legend([one[0],three[0]],['线性样条','三次样条']) 118 | plt.show() -------------------------------------------------------------------------------- /eight/readme.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c-dafan/numerical-computation-method/726d915cb23f1ad34098124d6d5df36d5a0fa084/eight/readme.md -------------------------------------------------------------------------------- /first/bijin.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 4 | plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 5 | 6 | f=lambda x:-0.1*x**4-0.15*x**3-0.5*x**2-0.25*x+1.2 7 | 8 | def fo_df(x,h): 9 | plt.plot([x-h,x],[f(x-h),f(x)],'r--',label='前') 10 | return (f(x)-f(x-h))/h 11 | 12 | def back_df(x,h): 13 | plt.plot([x,x+h],[f(x),f(x+h)],'k--',label='后') 14 | return (f(x+h)-f(x))/h 15 | 16 | def cen_df(x,h): 17 | a=(f(x-h)+f(x+h))/2 18 | plt.plot([x-h,x+h],[f(x-h)+f(x)-a,f(x+h)+f(x)-a],'g--',label='中') 19 | return (f(x+h)-f(x-h))/(2*h) 20 | 21 | 22 | xx=np.linspace(-0.5,1.5,20) 23 | yy=f(xx) 24 | plt.plot(xx,yy) 25 | print('前',fo_df(0.5,0.5)) 26 | print('后',back_df(0.5,0.5)) 27 | print('中',cen_df(0.5,0.5)) 28 | plt.legend(loc='best') 29 | plt.show() 30 | 31 | xx=np.linspace(-1,1,20) 32 | yy=f(xx) 33 | plt.plot(xx,yy) 34 | print('前',fo_df(0.5,0.25)) 35 | print('后',back_df(0.5,0.25)) 36 | print('中',cen_df(0.5,0.25)) 37 | plt.legend(loc='best') 38 | plt.show() -------------------------------------------------------------------------------- /first/taile.py: -------------------------------------------------------------------------------- 1 | from sympy import * 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | 5 | x=Symbol('x') 6 | 7 | f=-0.1*x**4-0.15*x**3-0.5*x**2-0.25*x+1.2 8 | 9 | def ff(x): 10 | return -0.1*x**4-0.15*x**3-0.5*x**2-0.25*x+1.2 11 | 12 | a=np.linspace(-5,5,100) 13 | 14 | 15 | c=input('please input 在哪里泰勒展开:') 16 | 17 | t=f.series(x,int(c),5) 18 | 19 | d=input('please input x:') 20 | h=t.subs(x,int(d)) 21 | print(h) 22 | g=ff(np.linspace(-5,5,100)) 23 | plt.plot(a,g) 24 | plt.xlim((-5,5)) 25 | plt.ylim((g.min(),g.max()+(g.max()-g.min())*0.1)) 26 | plt.scatter(float(d),h) 27 | 28 | # plt.text(float(d),h,'') 29 | plt.vlines(int(d),plt.ylim()[0],h,linestyle="--",colors='r') 30 | plt.plot([plt.xlim()[0],int(d)],[h,h],'r--') 31 | plt.show() 32 | 33 | -------------------------------------------------------------------------------- /five/Regression.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | import numpy as np 5 | from sklearn.base import RegressorMixin 6 | from sklearn.preprocessing import PolynomialFeatures 7 | import matplotlib.pyplot as plt 8 | plt.rcParams['font.sans-serif'] = ['SimHei'] 9 | plt.rcParams['font.family']='sans-serif' 10 | plt.rcParams['axes.unicode_minus'] = False 11 | 12 | '''Regression支持线性回归与多项式回归及多变量回归,degree为多项式的次数, 13 | 调用fit方法,计算得到各变量的系数 14 | 调用predict方法,计算结果 15 | 调用score方法,计算r方分数 16 | ''' 17 | class Regression(RegressorMixin): 18 | def __init__(self,degree=1):#degree为多项式的次数 19 | self.degree=degree 20 | pass 21 | def fit(self,X,y): 22 | if type(X)!=np.ndarray: 23 | X=np.array(X) 24 | if type(y)!=np.ndarray: 25 | y=np.array(y) 26 | if len(X.shape)==1: 27 | X=X.reshape([-1,1]) 28 | self.pol=PolynomialFeatures(degree=self.degree) 29 | X=self.pol.fit_transform(X) 30 | self.W=self.CreateWmat(X,y) 31 | def CreateWmat(self,X,y): 32 | mat=[] 33 | for i in range(X.shape[1]): 34 | row=[] 35 | for j in range(X.shape[1]): 36 | row.append((X[:,i]*X[:,j]).sum()) 37 | mat.append(row) 38 | mat=np.mat(mat) 39 | y_list=[] 40 | for i in range(X.shape[1]): 41 | y_list.append((X[:,i]*y).sum()) 42 | y_list=np.mat(y_list).reshape([-1,1]) 43 | return mat.I*y_list 44 | def predict(self,X): 45 | if type(X)!=np.ndarray: 46 | X=np.array(X) 47 | if len(X.shape)==1: 48 | X=X.reshape([-1,1]) 49 | X=self.pol.transform(X) 50 | X=np.mat(X) 51 | return X*self.W 52 | 53 | def plot(X,y,regression): 54 | true,=plt.plot(X,y,c='b') 55 | y_pre=regression.predict(np.arange(min(X),max(X),0.1)) 56 | predict,=plt.plot(np.arange(min(X),max(X),0.1),y_pre,c='r') 57 | plt.legend([true,predict],["原始数据","预测结果"]) 58 | plt.show() 59 | 60 | X=[0,0.2,0.4,0.6,0.8] 61 | y=[0.9,1.9,2.8,3.3,4.2] 62 | regression=Regression(1) 63 | regression.fit(X,y) 64 | y_pre=regression.predict(X) 65 | print('result:',y_pre) 66 | print('r2_score:',regression.score(X,y)) 67 | plot(X,y,regression) 68 | 69 | #二次 70 | 71 | X=[0,1,2,3,4,5] 72 | y=[2.1,7.7,13.6,27.2,40.9,61.1] 73 | regression=Regression(2) 74 | regression.fit(X,y) 75 | y_pre=regression.predict(X) 76 | print('result:',y_pre) 77 | print('r2_score:',regression.score(X,y)) 78 | plot(X,y,regression) 79 | 80 | 81 | X=[1,2,3,4,6,7,8] 82 | y=[2,3,6,7,5,3,2] 83 | regression=Regression(2) 84 | regression.fit(X,y) 85 | y_pre=regression.predict(X) 86 | print('result:',y_pre) 87 | print('r2_score:',regression.score(X,y)) 88 | plot(X,y,regression) -------------------------------------------------------------------------------- /five/readme.md: -------------------------------------------------------------------------------- 1 | 2 | 支持一元一次回归,一元多次回归,多元一次回归,多远多次回归 3 | 4 | 其中参数degree为次数,默认为1 -------------------------------------------------------------------------------- /four/beer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/c-dafan/numerical-computation-method/726d915cb23f1ad34098124d6d5df36d5a0fa084/four/beer.png -------------------------------------------------------------------------------- /four/beer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Sep 30 11:50:13 2017 4 | 5 | @author: 大帆 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | def f(x): 12 | return (x+1)*(x-4)*(x-5)*(x+3)*(x-2) 13 | 14 | def f1(x): 15 | return x**5-7*x**4-3*x**3+79*x**2-46*x-120 16 | 17 | a=[1,-7,-3,79,-46,-120] 18 | aa=[1,-3.5,2.75,2.125,-3.875,1.25] 19 | 20 | def Beers(a,r=-1,s=-1): 21 | for g in range(50): 22 | b=[] 23 | for i,v in enumerate(a): 24 | if i==0: 25 | b.append(v) 26 | elif i==1: 27 | b.append(v+r*b[-1]) 28 | else: 29 | b.append(v+r*b[-1]+s*b[-2]) 30 | 31 | b0=b[-1] 32 | b1=b[-2] 33 | c=[] 34 | for i,v in enumerate(b): 35 | if i==0: 36 | c.append(v) 37 | elif i==1: 38 | c.append(v+r*c[-1]) 39 | else: 40 | c.append(v+r*c[-1]+s*c[-2]) 41 | 42 | c1=c[-2] 43 | c2=c[-3] 44 | c3=c[-4] 45 | rs=np.matrix([[c2,c3],[c1,c2]]).I*\ 46 | np.matrix([[-b1],[-b0]]) 47 | dr=rs[0] 48 | ds=rs[1] 49 | if (abs(dr/r)<0.01)and(abs(ds/s)<0.01): 50 | break 51 | r=r+dr 52 | s=s+ds 53 | r=r.min() 54 | s=s.min() 55 | return((r+(r**2+4*s)**0.5)/2,\ 56 | (r-(r**2+4*s)**0.5)/2) 57 | 58 | 59 | x1,x2=Beers(a,2,15) 60 | print(x1,x2) 61 | 62 | plt.figure() 63 | x_range=np.arange(-3.1,5.3,0.1) 64 | plt.plot(x_range,f1(x_range),'r',alpha=0.5) 65 | plt.hlines(0,plt.xlim()[0],plt.xlim()[1]) 66 | plt.scatter([x1,x2],[0,0]) 67 | plt.show() 68 | 69 | plt.figure() 70 | x1,x2=Beers(a,-4.1,-3.2) 71 | print(x1,x2) 72 | x_range=np.arange(-3.1,5.3,0.1) 73 | plt.plot(x_range,f1(x_range),'r',alpha=0.5) 74 | plt.hlines(0,plt.xlim()[0],plt.xlim()[1]) 75 | plt.scatter([x1,x2],[0,0]) 76 | plt.show() 77 | 78 | plt.figure() 79 | x1,x2=Beers(a,6.1,-8.2) 80 | print(x1,x2) 81 | x_range=np.arange(-3.1,5.3,0.1) 82 | plt.plot(x_range,f1(x_range),'r',alpha=0.5) 83 | plt.hlines(0,plt.xlim()[0],plt.xlim()[1]) 84 | plt.scatter([x1,x2],[0,0]) 85 | plt.show() 86 | 87 | plt.figure() 88 | x1,x2=Beers(a,3,4) 89 | print(x1,x2) 90 | x_range=np.arange(-3.1,5.3,0.1) 91 | plt.plot(x_range,f1(x_range),'r',alpha=0.5) 92 | plt.hlines(0,plt.xlim()[0],plt.xlim()[1]) 93 | plt.scatter([x1,x2],[0,0]) 94 | plt.show() 95 | 96 | plt.figure() 97 | x1,x2=Beers(a,1,2) 98 | print(x1,x2) 99 | x_range=np.arange(-3.1,5.3,0.1) 100 | plt.plot(x_range,f1(x_range),'r',alpha=0.5) 101 | plt.hlines(0,plt.xlim()[0],plt.xlim()[1]) 102 | plt.scatter([x1,x2],[0,0]) 103 | plt.show() -------------------------------------------------------------------------------- /four/readme.md: -------------------------------------------------------------------------------- 1 | 2 | 稍微有点问题,应该可以求出多个跟,多次调用即可 3 | 4 | 思路:先可以求得x\*\*2+rx+s中的r和s,多项式除去(x\*\*2+rx+s)可以得到另一个多项式,再求此多项式的跟 5 | 6 | ![beer.png](./beer.png) -------------------------------------------------------------------------------- /nine/Gaussian_elimination.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Nov 15 19:10:46 2017 4 | 5 | @author: 大帆 6 | """ 7 | 8 | import numpy as np 9 | 10 | def Gaussian_elimination(A,Y): 11 | W=np.c_[A,Y] 12 | W=W.astype('float') 13 | for i,L in enumerate(range(A.shape[0])): 14 | for m in range(L+1,A.shape[0]): 15 | W[m]=W[m]-W[L]*(W[m,i]/W[L,i]) 16 | x=[] 17 | for i in range(A.shape[0])[::-1]: 18 | sum_=0 19 | for h,j in enumerate(range(i+1,A.shape[0])): 20 | sum_+=W[i,j]*x[-1-h] 21 | x.append((W[i,-1]-sum_)/W[i,i]) 22 | 23 | x.reverse() 24 | return x 25 | 26 | def Gaussian_elimination_c(A,Y): 27 | W=np.zeros(A.shape) 28 | W=W.astype('float') 29 | for i in range(A.shape[0]): 30 | W[i]=A[i]/A[i].max() 31 | h=[] 32 | W=np.c_[W,np.arange(A.shape[0])] 33 | for i in range(W.shape[0]): 34 | id_max=np.argmax(W[i:,i]) 35 | h.append(W[id_max+i,-1]) 36 | t=W[i].copy() 37 | W[i]=W[id_max+i] 38 | W[id_max+i]=t 39 | del W 40 | h=[int(i) for i in h] 41 | A=A[h] 42 | Y=Y[h] 43 | return Gaussian_elimination(A,Y) 44 | 45 | A=[[1,1,1], 46 | [2,1,3], 47 | [5,3,4]] 48 | Y=[6,13,23] 49 | A=np.array(A) 50 | Y=np.array(Y).reshape([-1,1]) 51 | print("高斯消去法得到x1,x2,x3为:") 52 | print(Gaussian_elimination_c(A,Y)) 53 | 54 | 55 | A=[[1,1], 56 | [2.0,100] 57 | ] 58 | Y=[2,100] 59 | A=np.array(A) 60 | Y=np.array(Y).reshape([-1,1]) 61 | print('*'*10) 62 | print("交换高斯消去法得到的 x1,x2为:") 63 | print(Gaussian_elimination_c(A,Y)) 64 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # 数值分析作业(python实现) 2 | 3 | > 环境 4 | >* python3.5 5 | >* matplotlib包 6 | >* numpy包 7 | >* sklearn包 8 | >* sympy包 9 | 10 | 11 | ## [第一次][1] 12 | 泰勒级数展开 13 | 差分逼近微分 14 | 15 | ## [第二次][2] 16 | 二分法求解 17 | 试位法求解 18 | 19 | ## [第三次][3] 20 | 迭代法求根 21 | 牛顿法求根 22 | 正割法 23 | 24 | ## [第四次][4] 25 | 贝尔斯托法多项式求跟 26 | 27 | ## [第五次][5] 28 | 多项式回归 29 | 30 | ## [第六次][6] 31 | 牛顿差商插值 32 | 33 | ## [第七次][7] 34 | 拉格朗日插值法 35 | 36 | ## [第八次][8] 37 | 三次样条插值法 38 | 二次样条插值法 39 | 40 | ## [第九次][9] 41 | 高斯消元法(求解线性代数方程组) 42 | 43 | ## [第十次](./ten/) 44 | LU分解 45 | 46 | 47 | [1]: ./first/ 48 | [2]: ./second/ 49 | [3]: ./third/ 50 | [4]: ./four/ 51 | [5]: ./five/ 52 | [6]: ./six/ 53 | [7]: ./senve/ 54 | [8]: ./eight/ 55 | [9]: ./nine/ -------------------------------------------------------------------------------- /second/erfen.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | f=lambda x:2**x-4 4 | f1=lambda x:np.log10(x) 5 | f2=lambda x:x**0.5-1 6 | 7 | def two_cen(head,end,fun): 8 | cen=(head+end)/2 9 | while True: 10 | if fun(cen)*fun(head)<0: 11 | end=cen 12 | elif fun(cen)*fun(head)>0: 13 | head=cen 14 | else: 15 | return cen 16 | least_cen=cen 17 | cen=(head+end)/2 18 | try: 19 | if abs((cen-least_cen)/cen)<0.00005: 20 | return cen 21 | except ZeroDivisionError as e: 22 | pass 23 | pass 24 | 25 | print(two_cen(-5,5,f)) 26 | 27 | print(two_cen(0.5,5,f1)) -------------------------------------------------------------------------------- /second/shiwei.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | f=lambda x:2**x-4 4 | f1=lambda x:x+1 5 | f2=lambda x:x**0.5-1 6 | 7 | def try_place(x0,x1,fun): 8 | xr=x1-fun(x1)*(x0-x1)/(fun(x0)-fun(x1)) 9 | while True: 10 | if fun(xr)==0: 11 | return xr 12 | x0=xr 13 | least_xr=xr 14 | xr=x1-fun(x1)*(x0-x1)/(fun(x0)-fun(x1)) 15 | try: 16 | if abs((xr-least_xr)/xr)<0.00005: 17 | return xr 18 | except ZeroDivisionError as e: 19 | pass 20 | pass 21 | 22 | print(try_place(-1.5,1,f)) 23 | 24 | print(try_place(-5,5,f1)) -------------------------------------------------------------------------------- /senve/lglr.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Oct 27 21:12:09 2017 4 | 5 | @author: 大帆 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pyplot as plt 10 | 11 | 12 | def lglr(X,y): 13 | """ 14 | ### X格式要求 15 | 传入的X为numpy.ndarray格式 16 | """ 17 | aa=X.reshape([-1,1])-X 18 | fenmu=[] 19 | for i in range(aa.shape[1]): 20 | fenmu.append(aa[i][aa[i]!=0].prod()) 21 | def result(x): 22 | """ 23 | ### x格式要求 24 | x可以是int型,也可以为数组或者numpy.ndarray 25 | """ 26 | if type(x)==int: 27 | x=[x] 28 | re=[] 29 | for xx in x: 30 | res=0 31 | for i in range(aa.shape[1]): 32 | ca=(xx-X) 33 | res+=np.r_[ca[:i],ca[i+1:]].prod()/fenmu[i]*y[i] 34 | re.append(res) 35 | return np.array(re) 36 | return result 37 | 38 | 39 | X=np.arange(1,8) 40 | y=np.log2(X) 41 | lg=lglr(X,y) 42 | x=np.arange(X.min(),X.max()+0.1,0.1) 43 | yy=lg(x) 44 | plt.scatter(X,y) 45 | plt.plot(x,yy) 46 | plt.show() 47 | 48 | 49 | X=np.arange(1,12) 50 | y=-(X-3)**2+20 51 | lg=lglr(X,y) 52 | x=np.arange(X.min(),X.max()+0.1,0.1) 53 | yy=lg(x) 54 | plt.scatter(X,y) 55 | plt.plot(x,yy) 56 | plt.show() 57 | 58 | -------------------------------------------------------------------------------- /six/Newton.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Oct 17 21:27:55 2017 4 | 5 | @author: 大帆 6 | """ 7 | 8 | import numpy as np 9 | import matplotlib.pylab as plt 10 | 11 | X=[1,2,3,4,5,7,8,9] 12 | y=[np.log(x) for x in X] 13 | 14 | def Newton(X,y): 15 | W=np.zeros([len(X),len(X)+1]) 16 | W[:,0]=X 17 | W[:,1]=y 18 | for i in range(W.shape[1]-2): 19 | for j in range(i,W.shape[0]-1): 20 | W[j+1,i+2]=(W[j+1,i+1]-W[j,i+1])/(W[j+1,0]-W[j-i,0]) 21 | 22 | def f(x): 23 | res=W[0,1] 24 | c=1 25 | for i in range(1,W.shape[0]): 26 | a=W[i,i+1] 27 | c*=(x-X[i-1]) 28 | # for j in range(i): 29 | # a=(x-X[j])*a 30 | # res+=a 31 | res+=a*c 32 | return res 33 | return f 34 | 35 | 36 | f=Newton(X,y) 37 | plt.scatter(X,y) 38 | x=np.arange(1,9,0.1) 39 | plt.plot(x,f(x)) 40 | plt.show() 41 | 42 | 43 | plt.figure() 44 | X=[1,2,3,4,5,7,8,9] 45 | y=[x**2 for x in X] 46 | f=Newton(X,y) 47 | plt.scatter(X,y) 48 | x=np.arange(1,9,0.1) 49 | plt.plot(x,f(x)) -------------------------------------------------------------------------------- /ten/LU.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Wed Nov 29 14:17:05 2017 4 | 5 | @author: 大帆 6 | """ 7 | 8 | import numpy as np 9 | 10 | def LU_solution(A,Y): 11 | W=np.zeros(A.shape) 12 | W=W.astype('float') 13 | for i in range(A.shape[0]): 14 | W[i]=A[i]/A[i].max() 15 | h=[] 16 | W=np.c_[W,np.arange(A.shape[0])] 17 | for i in range(W.shape[0]): 18 | id_max=np.argmax(W[i:,i]) 19 | h.append(W[id_max+i,-1]) 20 | t=W[i].copy() 21 | W[i]=W[id_max+i] 22 | W[id_max+i]=t 23 | del W 24 | h=[int(i) for i in h] 25 | A=A[h] 26 | Y=Y[h] 27 | def LU(A,Y): 28 | W=np.c_[A,Y] 29 | W=W.astype('float') 30 | L=np.zeros(A.shape) 31 | for i,_ in enumerate(range(A.shape[0])): 32 | L[i,i]=1 33 | for m in range(i+1,A.shape[0]): 34 | chu=W[m,i]/W[i,i] 35 | L[m,i]=chu 36 | W[m]=W[m]-W[i]*chu 37 | U=W[:,:-1] 38 | return L,U 39 | L,U=LU(A,Y) 40 | D=np.zeros(A.shape[0]) 41 | for i in range(A.shape[0]): 42 | sum1=0 43 | for j in range(i): 44 | sum1+=D[j]*L[i,j] 45 | D[i]=(Y[i]-sum1)/L[i,i] 46 | X=np.zeros(A.shape[0]) 47 | for i in range(A.shape[0])[::-1]: 48 | sum1=0 49 | for j in range(i+1,A.shape[0]): 50 | sum1+=X[j]*U[i,j] 51 | X[i]=(D[i]-sum1)/U[i,i] 52 | return X 53 | 54 | 55 | A=[[2.0,100], 56 | [1,1]] 57 | Y=[100,2] 58 | A=np.array(A) 59 | Y=np.array(Y).reshape([-1,1]) 60 | print("LU分解求解多元线性方程组:") 61 | print(LU_solution(A,Y)) 62 | 63 | 64 | A=[[1,1,1], 65 | [2,1,3], 66 | [5,3,4]] 67 | Y=[6,13,23] 68 | A=np.array(A) 69 | Y=np.array(Y).reshape([-1,1]) 70 | print("LU分解求解多元线性方程组:") 71 | print(LU_solution(A,Y)) -------------------------------------------------------------------------------- /third/readme.md: -------------------------------------------------------------------------------- 1 | 2 | 有三种方法:分别是迭代法,牛顿法,正割法 -------------------------------------------------------------------------------- /third/开放法.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | 7 | 8 | f=lambda x:x**2-2*x 9 | xi=lambda x:np.sqrt(2*x) 10 | xrange=np.arange(0,5.2,0.1) 11 | 12 | plt.figure() 13 | plt.plot(xrange,f(xrange)) 14 | plt.hlines(0,0,plt.xlim()[1]) 15 | def plot(x,color='g'): 16 | plt.hlines(f(x),0,x,color,'--') 17 | plt.vlines(x,0,f(x),color,'--') 18 | 19 | def Fixed_point(xstart,func): 20 | while True: 21 | plot(xstart) 22 | xiii=func(xstart) 23 | if abs((xiii-xstart)/xstart)<0.00005: 24 | return xiii 25 | xstart=xiii 26 | 27 | print(Fixed_point(5,xi)) 28 | plt.show() 29 | 30 | 31 | fd=lambda x:2*x-2 32 | plt.figure() 33 | plt.plot(xrange,f(xrange)) 34 | plt.hlines(0,0,plt.xlim()[1]) 35 | def Newton(xstart,func): 36 | while True: 37 | plot(xstart) 38 | xiii=xstart-f(xstart)/fd(xstart) 39 | if abs((xiii-xstart)/xstart)<0.00005: 40 | return xiii 41 | xstart=xiii 42 | pass 43 | 44 | print(Newton(5,f)) 45 | plt.plot() 46 | 47 | def plot2(x1,x2,func): 48 | xl=(func(x2)-func(x1))/(x2-x1) 49 | x=x1-func(x1)/xl 50 | plt.plot([x,x2],[0,func(x2)],'r--') 51 | plt.show() 52 | 53 | plt.figure() 54 | plt.plot(xrange,f(xrange),'k') 55 | plt.hlines(0,0,plt.xlim()[1]) 56 | def Secant(xstart1,xstart2,func): 57 | while True: 58 | plot(xstart1,'b') 59 | plot(xstart2,'b') 60 | plot2(xstart2,xstart1,func) 61 | xiii=xstart1-func(xstart1)*\ 62 | (xstart2-xstart1)/(func(xstart2)-func(xstart1)) 63 | if abs((xiii-xstart1)/xstart1)<0.00005: 64 | return xiii 65 | xstart1=xstart2 66 | xstart2=xiii 67 | pass 68 | 69 | print(Secant(5,3,f)) 70 | plt.plot() 71 | 72 | 73 | --------------------------------------------------------------------------------