python插值程序_計算方法(2)——插值法(附Python程序)

給定一些數據,生成函數的方式有兩種:插值,回歸。

插值而得到的函數通過數據點,回歸得到的函數不一定通過數據點。

下面給出拉格朗日插值,牛頓插值和Hermite插值的程序,

具體原理可參考課本,不再贅述。

拉格朗日插值法

線性插值 一次精度 需要2個節點

二次插值 二次精度 需要3個節點

n次插值 n次精度 需要n+1個節點

拉格朗日插值代碼段(根據傳入數據自動判斷次數):

# 返回多項式

def p(x,a):

"""p(x,a)是x的函數,a是各冪次的系數"""

s = 0

for i in range(len(a)):

s += a[i]*x**i

return s

# n次拉格朗日插值

def lagrange_interpolate(x_list,y_list,x):

"""x_list 待插值的x元素列表y_list 待插值的y元素列表插值以后整個lagrange_interpolate是x的函數"""

if len(x_list) != len(y_list):

raise ValueError("list x and list y is not of equal length!")

# 系數矩陣

A = []

for i in range(len(x_list)):

A.append([])

for j in range(len(x_list)):

A[i].append(pow(x_list[i],j))

b = []

for i in range(len(x_list)):

b.append([y_list[i]])

# 求得各階次的系數

a = lu_solve(A, b) # 用LU分解法解線性方程組,可以使用numpy的類似函數

a = transpose(a)[0] # change col vec a into 1 dimension

val = p(x,a)

print(x,val)

return val

其中lu_solve(A,b)是自己寫的輪子,可以用numpy的numpy.linalg.sovle(A,b)來代替

到后面會有一期講矩陣方程直接法,會有講到如何寫lu_solve()

看一看插值的效果如何

import numpy as np

import matplotlib.pyplot as plt

# 待插值的元素值

x_points = [0,1,2,3,4,5]

y_points = [1,5,4,8,7,12]

# 拉格朗日插值

x = np.linspace(0,5)

y = list(map(lambda t: lagrange_interpolate(x_points,y_points,t),x))

# 畫圖

plt.scatter(x_points,y_points,color = "orange")

plt.plot(x,y)

plt.legend(["lagrange interpolation","scattered points"])

plt.show()拉格朗日插值

可以看到,插值之后的函數可以較好地反映原數據點的情況。

牛頓插值法

涉及到的兩個表,差分表和差商表:差分表差商表

遞歸打印差分表

def difference_list(dlist): # Newton

if len(dlist)>0:

print(dlist)

prev,curr = 0,0

n = []

for i in dlist:

curr = i

n.append(curr - prev)

prev = i

n.pop(0)

difference_list(n)

打印差商表,并以列表的形式返回圖中藍色圈起來的部分

def difference_quotient_list(y_list,x_list = []):

if x_list == []:

x_list = [i for i in range(len(y_list))]

print(y_list)

prev_list = y_list

dq_list = []

dq_list.append(prev_list[0])

for t in range(1,len(y_list)):

prev,curr = 0,0

m = []

k = -1

for i in prev_list:

curr = i

m.append((curr - prev)/(x_list[k+t]-x_list[k]))

prev = i

k+=1

m.pop(0)

prev_list = m

dq_list.append(prev_list[0])

print(m)

return dq_list

牛頓插值代碼段(調用了之前求差商表的代碼)

def newton_interpolate(x_list,y_list,x):

coef = difference_quotient_list(y_list,x_list)

p = coef[0]

for i in range(1,len(coef)):

product = 1

for j in range(i):

product *= (x - x_list[j] )

p += coef[i]*product

return p

if __name__ == '__main__':

import numpy as np

import matplotlib.pyplot as plt

# 待插值的元素值

x_points = [0,1,2,3,4,5]

y_points = [1,5,4,8,7,12]

# 牛頓插值

x = np.linspace(0,5)

y = list(map(lambda t: newton_interpolate(x_points,y_points,t),x))

# 畫圖

plt.scatter(x_points,y_points,color = "orange")

plt.plot(x,y)

plt.legend(["newton interpolation","scattered points"])

plt.show()

插值效果圖牛頓插值

可以看到,相同的插值節點,使用拉格朗日插值和牛頓插值的結果是相同的。

Hermite 插值法

三次Hermite插值不但要求在插值節點上插值多項式與函數值相等,還要求插值多項式的導數與函數導數相等。

進行Hermite插值需要六個信息:

這個比較好理解,通過

兩點的插值有無限種方式。比如:

但是,通過限制住兩個端點的導數值,就可以確定下來大致的插值形狀。(對于Hermite插值,六個條件能確定出唯一的插值結果)

例如,可以編程求出

def hermite(x0,x1,y0,y1,y0_prime,y1_prime,x):

alpha0 = lambda x: ((x-x1)/(x0-x1))**2 * (2*(x-x0)/(x1-x0)+1)

alpha1 = lambda x: ((x-x0)/(x1-x0))**2 * (2*(x-x1)/(x0-x1)+1)

beta0 = lambda x: ((x-x1)/(x0-x1))**2 * (x-x0)

beta1 = lambda x: ((x-x0)/(x1-x0))**2 * (x-x1)

H = alpha0(x)*y0 + alpha1(x)*y1 + beta0(x)*y0_prime + beta1(x)*y1_prime

return H

if __name__ == '__main__':

import numpy as np

import matplotlib.pyplot as plt

f = lambda x: hermite(0,1,0,1,-1,-4,x)

x = np.linspace(0,1)

y = list(map(f,x))

plt.scatter([0,1],[0,1],color = "orange")

plt.plot(x,y)

plt.show()

龍格現象(Runge phenomenon)

然而,并不是所有的函數都可以通過提高插值次數來提高插值準確度。

比如著名的龍格函數

,從[-1,1]取10個點,插值出來的函數是這樣的:

這就是龍格現象,主要原因是誤差項里面的高階導數導致的。什么是龍格現象(Rungephenomenon)?如何避免龍格現象?_MachineLearningwithTuring'sCat-CSDN博客_龍格現象?www.baidu.comhttps://en.wikipedia.org/wiki/Runge%27s_phenomenon?en.wikipedia.org

其實不單單是

,很多偶函數都有這樣的性質:

比如

用于生成上圖的代碼:

# 龍格現象的產生

if __name__ == "__main__":

import numpy as np

import matplotlib.pyplot as plt

f = lambda x: 1/(1+25*x**2)

# 待插值的元素值

x_points = np.linspace(-1,1,11)

print(x_points)

y_points = list(map(f,x_points))

# 牛頓插值

x = np.linspace(-1,1)

y = list(map(lambda t: lagrange_interpolate(x_points,y_points,t),x))

# 畫圖

plt.figure("lagrange interpolation")

plt.scatter(x_points,y_points,color = "orange")

plt.plot(x,y)

plt.legend(["lagrange interpolation","scattered points"])

plt.show()

如何避免龍格現象,就需要用到分段插值了。

下一篇將講解分段插值。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/542341.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542341.shtml
英文地址,請注明出處:http://en.pswp.cn/news/542341.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

java中cbrt_Java Math類靜態double cbrt(double d)示例

java中cbrt數學類靜態double cbrt(double d) (Math Class static double cbrt(double d)) This method is available in java.lang package. 此方法在java.lang包中可用。 This method is used to find the cube root of the given parameter in the method. 此方法用于查找方法…

html中電子郵件怎么寫,談html mailto(電子郵件)實際應用

大家知道,mailto是網頁設計制作中的一個非常實用的html標簽,許多擁有個人網頁的朋友都喜歡在網站的醒目位置處寫上自己的電子郵件地址,這樣網頁瀏覽者一旦用鼠標單擊一下由mailto組成的超級連接后,就能自動打開當前計算機系統中默…

python爬蟲urllib 數據處理_Python 爬蟲筆記之Urllib的用法

urllib總共有四個子模塊,分別為request,error,parse,robotparserrequest用于發送request(請求)和取得response(回應)error包含request的異常,通常用于捕獲異常parse用于解析和處理urlrobotparser用于robot.txt文件的處理urllib.request 模塊import urllib.requestresponseurlli…

語法分析-C語言程序

⑴<C語言程序>——〉begin<語句串>end ⑵<語句串>——〉<語句>{&#xff1b;<語句>} ⑶<語句>——〉<賦值語句> ⑷<賦值語句>——〉ID&#xff1a;<表達式> ⑸<表達式>——〉<項>{<項> | -<項>…

python中對比數組長度_在Python中檢索數組長度的首選方法

python中對比數組長度The __len__() is a method on container types. However, python also provides another option of retrieving the length of an array, using the method len(). __len __()是關于容器類型的方法。 但是&#xff0c;python還使用len()方法提供了另一個檢…

html window 屬性,html中window對象top 、self 、parent 等屬性

top 屬性返回最頂層的先輩窗口。該屬性返回對一個頂級窗口的只讀引用。如果窗口本身就是一個頂級窗口&#xff0c;top 屬性存放對窗口自身的引用。如果窗口是一個框架&#xff0c;那么 top 屬性引用包含框架的頂層窗口。下面的例子窗口是否在一個框架中&#xff0c;如果是&…

python隨機抽簽列表中的同學值日_神奇的大抽簽--Python中的列表_章節測驗,期末考試,慕課答案查詢公眾號...

神奇的大抽簽--Python中的列表_章節測驗,期末考試,慕課答案查詢公眾號更多相關問題下圖表示幾個植物類群的進化關系。下列敘述不正確的是[ ]A&#xff0e;最先出現的植物類群是甲B&#xff0e;乙和丙都是由甲進化來的請結合下圖中的有關動物回答問題。(1)___的發育為不完全變態…

LightGBM中GBDT的實現

現在LightGBM開源了&#xff0c;這里將之前的一個文檔發布出來供大家參考&#xff0c;幫助更快理解LightGBM的實現&#xff0c;整體思路應該是類似的。 LightGBM優雅&#xff0c;快速&#xff0c;效果好&#xff0c;希望LightGBM越來越好:) LightGBM中GBDT的實現 http://www.do…

python逗號分隔符_在Python中用逗號將數字打印為數千個分隔符

python逗號分隔符什么是質數&#xff1f; (What is a prime number?) Many times, while writing the code we need to print the large number separated i.e. thousands separators with commas. 很多時候&#xff0c;在編寫代碼時&#xff0c;我們需要打印大量的分隔符&…

html頁面foot,HTML tfoot用法及代碼示例

HTML中的標記用于提供頁腳內容組。此標記在帶有標題和正文的HTML表中使用&#xff0c;稱為“thead”和“tbody”。 標記是表的子標記&#xff0c;是和的父標記。用法: // Table footer contents... 屬性&#xff1a;標記包含HTML4.1支持但HTML5不支持的許多屬性。align:設置文本…

Tensorflow學習筆記4:分布式Tensorflow

簡介 Tensorflow API提供了Cluster、Server以及Supervisor來支持模型的分布式訓練。 關于Tensorflow的分布式訓練介紹可以參考Distributed Tensorflow。簡單的概括說明如下&#xff1a; Tensorflow分布式Cluster由多個Task組成&#xff0c;每個Task對應一個tf.train.Server實例…

c語言指針訪問 靜態變量_使用C中的指針訪問變量的值

c語言指針訪問 靜態變量As we know that a pointer is a special type of variable that is used to store the memory address of another variable. A normal variable contains the value of any type like int, char, float etc, while a pointer variable contains the me…

迭代器 java_Java設計模式8:迭代器模式

迭代器模式迭代器模式又叫做游標(Cursor)模式&#xff0c;其作用是提供一種方法訪問一個容器元素中的各個對象&#xff0c;而又不暴露該對象的內部細節。迭代器模式結構迭代器模式由以下角色組成&#xff1a;1、迭代器角色負責定義訪問和遍歷元素的接口2、具體迭代器角色實現迭…

html二級下拉菜單模板,基于jQuery實現二級下拉菜單效果

本文通過代碼實例詳細介紹一下簡單的二級下拉菜單是如何實現的&#xff0c;當然還有更為復雜的二級菜單&#xff0c;不過先學會如何制作簡單的&#xff0c;分享給大家供大家參考&#xff0c;具體內容如下代碼如下&#xff1a;下拉菜單nav a{text-decoration:none;}nav>ul>…

給定一個整數判斷是否為素數_Ruby程序檢查給定數字是否為素數

給定一個整數判斷是否為素數檢查素數 (Checking prime number) Before getting into writing the code, let us understand what exactly the prime numbers are? So that we could easily design its logic and implement it in the code. Prime numbers are those numbers w…

python 正則findall右斜杠_python中正則表達式的使用

本文將介紹幾個最常用的正則符號&#xff0c;以及正則表達式的應用場景。如果說【數學表達式】刻畫的是數字的內在規律&#xff0c;那么【正則表達式】則是用來刻畫和描述字符串內在規律的表達式。記得剛接觸python時學習過slice&#xff0c;replace&#xff0c;split等方法&am…

JavaScript | 用戶定義函數的一些示例

1) Design a function, print message and assign the function to a variable and print it like a function 1)設計一個功能&#xff0c;打印消息并將該功能分配給變量&#xff0c;然后像打印功能一樣打印 <html lang"en"><head><script>functi…

網易 html5,別再想不開做H5了

寫這篇文章的時候網易噠噠《飼養手冊》H5刷屏了&#xff0c;但我們依舊不建議品牌做H5。H5作為大眾傳播工具的時代&#xff0c;已經過去了。盡管去年有很多H5曾經刷屏過&#xff0c;但在當時我們就一直跟朋友說&#xff0c;不要再嘗試H5了&#xff0c;性價比根本算不過來&#…

python打開word后再關閉再打開出錯_用Python寫了個程序調用word,運行完后再手動打開word文檔就變慢了,這是為啥?...

公司歸檔文件比較麻煩&#xff0c;于是用Python寫了個程序自動歸檔&#xff0c;運行無錯誤。但是運行完后問題就來了&#xff0c;自己手動打開word文檔時速度變得奇慢&#xff0c;打開一個文檔需要1~2min,請各位同仁幫我看看。下為源代碼#歸檔.pyimport osimport refrom win32c…

編程 mcq_MCQ | 8255 PPI(可編程外圍接口)

編程 mcqQuestion 1: How many pins does the 8255 PPI IC contains? 問題1&#xff1a;8255 PPI IC包含多少個引腳&#xff1f; 24 24 20 20 32 32 40 40 Answer: d. 40 答案&#xff1a;d。 40 Question 2: In which mode do all the Ports of the 8255 PPI work as Input…