假設我們已知坐標 (x0, y0) 與 (x1, y1),要得到 [x0, x1] 區間內某一位置 x 在直線上的值。根據圖中所示,我們得到
由於 x 值已知,所以可以從公式得到 y 的值
已知 y 求 x 的過程與以上過程相同,只是 x 與 y 要進行交換。
python的代碼實現:
import matplotlib.pyplot as plt """ @brief: 計算n階差商 f[x0, x1, x2 ... xn] @param: xi 所有插值節點的橫坐標集合 o @param: fi 所有插值節點的縱坐標集合 / \ @return: 返回xi的i階差商(i為xi長度減1) o o @notice: a. 必須確保xi與fi長度相等 / \ / \ b. 由於用到了遞歸,所以留意不要爆棧了. o o o o c. 遞歸減遞歸(每層遞歸包含兩個遞歸函數), 每層遞歸次數呈二次冪增長,總次數是一個滿二叉樹的所有節點數量(所以極易棧溢出) """ def get_order_diff_quot(xi = [], fi = []): if len(xi) > 2 and len(fi) > 2: return (get_order_diff_quot(xi[:len(xi) - 1], fi[:len(fi) - 1]) - get_order_diff_quot(xi[1:len(xi)], fi[1:len(fi)])) / float(xi[0] - xi[-1]) return (fi[0] - fi[1]) / float(xi[0] - xi[1]) """ @brief: 獲得Wi(x)函數; Wi的含義舉例 W1 = (x - x0); W2 = (x - x0)(x - x1); W3 = (x - x0)(x - x1)(x - x2) @param: i i階(i次多項式) @param: xi 所有插值節點的橫坐標集合 @return: 返回Wi(x)函數 """ def get_Wi(i = 0, xi = []): def Wi(x): result = 1.0 for each in range(i): result *= (x - xi[each]) return result return Wi """ @brief: 獲得牛頓插值函數 @ """ def get_Newton_inter(xi = [], fi = []): def Newton_inter(x): result = fi[0] for i in range(2, len(xi)): result += (get_order_diff_quot(xi[:i], fi[:i]) * get_Wi(i-1, xi)(x)) return result return Newton_inter """ demo: """ if __name__ == '__main__': ''' 插值節點, 這里用二次函數生成插值節點,每兩個節點x軸距離位10 ''' sr_x = [i for i in range(-50, 51, 10)] sr_fx = [i**2 for i in sr_x] Nx = get_Newton_inter(sr_x, sr_fx) # 獲得插值函數 tmp_x = [i for i in range(-50, 51)] # 測試用例 tmp_y = [Nx(i) for i in tmp_x] # 根據插值函數獲得測試用例的縱坐標 ''' 畫圖 ''' plt.figure("I love china") ax1 = plt.subplot(111) plt.sca(ax1) plt.plot(sr_x, sr_fx, linestyle = '', marker='o', color='b') plt.plot(tmp_x, tmp_y, linestyle = '--', color='r') plt.show() ~ ~ "linear_test.py" 81L, 2764C written 45,5 Bot
參考文檔: