最佳平方逼近-python
Posted 嘟嘟肚腩仔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最佳平方逼近-python相关的知识,希望对你有一定的参考价值。
分享一下最近学习的数值分析课后作业
一次逼近
import numpy as np
from sympy import *
import math
import matplotlib.pyplot as plt
#n代表n-1次逼近
n = 2
#建立hilbert矩阵
H = np.zeros((n,n))
for i in range(n):
for j in range(n):
H[i][j] = 1/(i+j+1)
f = np.zeros((n,1))
for i in range(n):
x = symbols("x")
f[i][0] = integrate((math.e**x)*(x**i),(x,0,1))
#a为系数向量
a = np.linalg.inv(H).dot(f)
print(a)
x = np.linspace(0,1,20)
y = math.e**(x)
def fun(a,x):
return a[0]+x*a[1]
y_pred = fun(a,x)
plt.plot(x,y,'b')
plt.plot(x,y_pred,'r')
二次逼近
import numpy as np
from sympy import *
import math
import matplotlib.pyplot as plt
#n代表n-1次逼近
n = 3
#建立hilbert矩阵
H = np.zeros((n,n))
for i in range(n):
for j in range(n):
H[i][j] = 1/(i+j+1)
f = np.zeros((n,1))
for i in range(n):
x = symbols("x")
f[i][0] = integrate((math.e**x)*(x**i),(x,0,1))
#a为系数向量
a = np.linalg.inv(H).dot(f)
print(a)
x = np.linspace(0,1,20)
y = math.e**(x)
def fun(a,x):
return a[0]+x*a[1]+x**2*a[2]
y_pred = fun(a,x)
plt.plot(x,y,'b')
plt.plot(x,y_pred,'r')
三次逼近
import numpy as np
from sympy import *
import math
import matplotlib.pyplot as plt
#n代表n-1次逼近
n = 4
#建立hilbert矩阵
H = np.zeros((n,n))
for i in range(n):
for j in range(n):
H[i][j] = 1/(i+j+1)
f = np.zeros((n,1))
for i in range(n):
x = symbols("x")
f[i][0] = integrate((math.e**x)*(x**i),(x,0,1))
#a为系数向量
a = np.linalg.inv(H).dot(f)
print(a)
x = np.linspace(0,1,20)
y = math.e**(x)
def fun(a,x):
return a[0]+x*a[1]+x**2*a[2]+x**3*a[3]
y_pred = fun(a,x)
plt.plot(x,y,'b')
plt.plot(x,y_pred,'r')
以上是关于最佳平方逼近-python的主要内容,如果未能解决你的问题,请参考以下文章
Python代码中的数学之美:用牛顿逼近法计算2的算术平方根