在假期利用Python完成了《数值分析》第二章的计算实习题,主要实现了牛顿插值法和三次样条插值,给出了自己的实现与调用Python包的实现——现在能搜到的基本上都是MATLAB版,或者是各种零碎的版本。

代码如下:

(第一题使用的自己的程序,第二第三题使用的Python自带库)

import math

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from numpy.linalg import solve
from scipy import interpolate
from scipy.interpolate import lagrange plt.rc('figure',figsize=(20,15)) print("Problem I:") given_x=[0.2,0.4,0.6,0.8,1.0]
given_y=[0.98,0.92,0.81,0.64,0.38]
given_times=4
x_range=(0,1.1,0.02) #@brief: Convert(begin,end,interval) to a list, but interval can be float numbers.
def process_xpara(xpara):
max_times=0
if 0<xpara[2]<1:
tmp_xpara_interval=xpara[2]
while tmp_xpara_interval-int(tmp_xpara_interval)!=0:
max_times=max_times+1
tmp_xpara_interval=tmp_xpara_interval*10
max_times=10**max_times
return [i/max_times for i in range(int(xpara[0]*max_times),int(xpara[1]*max_times),int(xpara[2]*max_times))] def divide_difference(x,y,times):
now=[(x[i],y[i]) for i in range(len(x))]
ans=[now[0]]
for order in range(1,times+1):
tmp=[]
for i in range(1,len(now)):
tmp.append((x[order+i-1]-x[i-1],(now[i][1]-now[i-1][1])/(x[order+i-1]-x[i-1])))
now=tmp
ans.append(now[0])
return ans def get_func_value_newton(xcoef,x,xorigin):
ans=0
for i in range(len(xcoef)):
tmp=xcoef[i][1]
for j in range(i):
tmp=tmp*(x-xorigin[j])
ans=ans+tmp
return ans
"""
#@param: xpara(xbegin,xend,xinterval) fpara[f[x_1~i]]
"""
# spec_i=[0.2+0.08*x for x in (0,1,10,11)] def newton_interpolate(xpara,fpara,xorigin):
x_discrete_value=process_xpara(xpara)
return [(x,get_func_value_newton(fpara,x,xorigin)) for x in x_discrete_value] parameters=divide_difference(given_x,given_y,given_times)
newton_interpolate_value=newton_interpolate(x_range,parameters,given_x) fig=plt.figure()
sub_fig1=fig.add_subplot(2,2,1)
sub_fig1.set_title("Problem I")
sub_fig1.plot([var[0] for var in newton_interpolate_value],[var[1] for var in newton_interpolate_value],label='Newton') # l_f=lagrange(given_x,given_y)
# tmpara=process_xpara(x_range)
# plt.plot(tmpara,[l_f(x) for x in tmpara]) # 三次样条插值
n=len(given_x)
h=[]
f0p=0
fnp=0
for i in range(1,len(given_x)):
h.append(given_x[i]-given_x[i-1])
miu=[0] # 0 should not be used
lam=[1]
d=[6/h[0]*((given_y[1]-given_y[0])/(given_x[1]-given_x[0])-f0p)]
for j in range(1,len(h)):
miu.append(h[j-1]/(h[j-1]+h[j]))
lam.append(h[j]/(h[j-1]+h[j]))
d.append(6*((given_y[j+1]-given_y[j])/(given_x[j+1]-given_x[j])-(given_y[j-1]-given_y[j])/(given_x[j-1]-given_x[j]))/(h[j-1]+h[j]))
miu.append(1)
d.append(6/h[-1]*(fnp-(given_y[-1]-given_y[-2])/(given_x[-1]-given_x[-2]))) A=np.zeros((n,n))
for i in range(n):
A[i][i]=2
if i!=n-1:
A[i][i+1]=lam[i]
if i!=0:
A[i][i-1]=miu[i]
C=solve(A,np.array(d).T)
# print(C) def get_func_value_cubic_spline(mtuple, xtuple, ytuple, x):
return mtuple[0]/(6*(xtuple[1]-xtuple[0]))*(xtuple[1]-x)**3+mtuple[1]/(6*(xtuple[1]-xtuple[0]))*(x-xtuple[0])**3+(ytuple[0]-(mtuple[0]*(xtuple[1]-xtuple[0])**2/6))*(xtuple[1]-x)/(xtuple[1]-xtuple[0])+(ytuple[1]-(mtuple[1]*(xtuple[1]-xtuple[0])**2/6))*(x-xtuple[0])/(xtuple[1]-xtuple[0]) def cubic_spline_interpolate(xpara, mpara, x, y):
fun_value=[]
x_discrete_value=process_xpara(xpara)
for j in range(len(x)-1):
ok_value=[(element,get_func_value_cubic_spline((mpara[j],mpara[j+1]),(x[j],x[j+1]),(y[j],y[j+1]),element)) for element in x_discrete_value if x[j]<=element<x[j+1]]
fun_value=fun_value+ok_value
return fun_value
cubic_spline_interpolate_value=cubic_spline_interpolate(x_range,C.tolist(),given_x,given_y) sub_fig1.plot([var[0] for var in cubic_spline_interpolate_value],[var[1] for var in cubic_spline_interpolate_value],label='Cubic') sub_fig1.legend(loc='best') def get_func_x(x):
return 1/(1+25*x*x) given_x=np.linspace(-1,1,10)
given_y=get_func_x(given_x) #p.array([get_func_x(x) for x in given_x])
display_x=np.linspace(-1,1,100)
display_y=get_func_x(display_x) sub_fig2=fig.add_subplot(2,2,2)
sub_fig2.set_title("Problem II(Alpha): Using System Functions") c_x=interpolate.interp1d(given_x, given_y, kind = 'cubic')
l_x=lagrange(given_x,given_y)
sub_fig2.plot(display_x,l_x(display_x))
sub_fig2.plot(display_x,c_x(display_x))
sub_fig2.plot(display_x,display_y) sub_fig3=fig.add_subplot(2,2,3)
sub_fig3.set_title("Problem II(Beta): Using System Functions") given_x=np.linspace(-1,1,20)
given_y=get_func_x(given_x) #p.array([get_func_x(x) for x in given_x])
c_x=interpolate.interp1d(given_x, given_y, kind = 'cubic')
l_x=lagrange(given_x,given_y)
sub_fig3.plot(display_x,l_x(display_x))
sub_fig3.plot(display_x,c_x(display_x))
sub_fig3.plot(display_x,display_y) fig_problem_three=plt.figure() given_x=[0,1,4,9,16,25,36,49,64]
given_y=[0,1,2,3,4,5,6,7,8]
display_big_x=np.linspace(0,64,200)
display_small_x=np.linspace(0,1,50)
sub_fig4=fig_problem_three.add_subplot(2,1,1)
l_x=lagrange(given_x,given_y)
c_x=interpolate.interp1d(given_x, given_y, kind = 'cubic')
sub_fig4.plot(display_big_x,l_x(display_big_x),label='Lagrange')
sub_fig4.plot(display_big_x,c_x(display_big_x),label='Cubic')
sub_fig4.plot(display_big_x,np.sqrt(display_big_x),label='Origin')
sub_fig4.legend(loc='best') sub_fig5=fig_problem_three.add_subplot(2,1,2)
sub_fig5.plot(display_small_x,l_x(display_small_x),label='Lagrange')
sub_fig5.plot(display_small_x,c_x(display_small_x),label='Cubic')
sub_fig5.plot(display_small_x,np.sqrt(display_small_x),label='Origin')
sub_fig5.legend(loc='best')

「学习记录」《数值分析》第二章计算实习题(Python语言)的更多相关文章

  1. 「学习记录」《数值分析》第三章计算实习题(Python语言)

    第三题暂缺,之后补充. import matplotlib.pyplot as plt import numpy as np import scipy.optimize as so import sy ...

  2. 「学习笔记」字符串基础:Hash,KMP与Trie

    「学习笔记」字符串基础:Hash,KMP与Trie 点击查看目录 目录 「学习笔记」字符串基础:Hash,KMP与Trie Hash 算法 代码 KMP 算法 前置知识:\(\text{Border} ...

  3. 「学习笔记」FFT 之优化——NTT

    目录 「学习笔记」FFT 之优化--NTT 前言 引入 快速数论变换--NTT 一些引申问题及解决方法 三模数 NTT 拆系数 FFT (MTT) 「学习笔记」FFT 之优化--NTT 前言 \(NT ...

  4. 「学习笔记」FFT 快速傅里叶变换

    目录 「学习笔记」FFT 快速傅里叶变换 啥是 FFT 呀?它可以干什么? 必备芝士 点值表示 复数 傅立叶正变换 傅里叶逆变换 FFT 的代码实现 还会有的 NTT 和三模数 NTT... 「学习笔 ...

  5. 学习opencv中文版教程——第二章

    学习opencv中文版教程——第二章 所有案例,跑起来~~~然而并没有都跑起来...我只把我能跑的都尽量跑了,毕竟看书还是很生硬,能运行能出结果,才比较好. 越着急,心越慌,越是着急,越要慢,越是陌生 ...

  6. 「学习笔记」Min25筛

    「学习笔记」Min25筛 前言 周指导今天模拟赛五分钟秒第一题,十分钟说第二题是 \(\text{Min25}​\) 筛板子题,要不是第三题出题人数据范围给错了,周指导十五分钟就 \(\text{AK ...

  7. 「学习笔记」Treap

    「学习笔记」Treap 前言 什么是 Treap ? 二叉搜索树 (Binary Search Tree/Binary Sort Tree/BST) 基础定义 查找元素 插入元素 删除元素 查找后继 ...

  8. ArcGIS API for JavaScript 4.2学习笔记[3] 官方第二章Mapping and Views概览与解释

    目录如下: 连接:第二章 Mapping and Views 根据本人体会, [这一章节主要是介绍地图(Map)和视图(View)的.] 其中,Get started with MapView(2D) ...

  9. 「学习笔记」wqs二分/dp凸优化

    [学习笔记]wqs二分/DP凸优化 从一个经典问题谈起: 有一个长度为 \(n\) 的序列 \(a\),要求找出恰好 \(k\) 个不相交的连续子序列,使得这 \(k\) 个序列的和最大 \(1 \l ...

随机推荐

  1. JavaScript数组实战小练习

    1.找出元素在数组中的位置. function indexOf(arr, item) { if(Array.prototype.indexOf){ //判断浏览器是否支持indexOf方法 retur ...

  2. Android学习笔记_81_Android ProgressDialog ProgressBar 各种效果

    1,弹出Dialog 屏幕不变暗. 创建一个样式就OK了:在styles.xml文件里添加样式: 1, <style name="dialog" parent="@ ...

  3. 12 个强大的 Chrome 插件扩展

    Chrome功能强大,也得益于其拥有丰富的扩展资源库.Chrome Web Store里有各种各样的插件,可以满足你使用Chrome时的各种要求.和Firefox一样,Chrome的扩展非常容易安装, ...

  4. LVS-DR模式实现调度负载

    本篇文章主要梳理一下LVS前端调度过程及用户请求过程 实验架构 准备工作 添加各主机路由联通主机通信 Client IP route add default gw 172.20.17.19 Route ...

  5. hibernate中配置单向多对一关联,和双向一对多,双向多对多

    什么是一对多,多对一? 一对多,比如你去找一个父亲的所有孩子,孩子可能有两个,三个甚至四个孩子. 这就是一对多 父亲是1 孩子是多 多对一,比如你到了两个孩子,它们都是有一个共同的父亲. 此时孩子就是 ...

  6. Git----将本地代码推送到远程仓库

    1.初始化本地 git init 2.添加文件 -A等于 -. 和-a的集合 git add -A 3.提交 git commit -m 'add' 4.关联到远程库 git remote add o ...

  7. Node.js(二)----安装Cnpm

    ---恢复内容开始--- 1.安装CNPM 因为天草的 Great Wall 导致下载速度龟速....所以安装Cnpm淘宝镜像 2.命令 2.1 如果版本合适 设置镜像地址 npm config se ...

  8. Oracle数据库之 PL SQL 学习笔记

    1.定义基本变量: 2.引用型的变量: set serveroutput on   declare pename emp.ename%type; psal emp.sal%type;   begin ...

  9. zookeeper环境搭建(Linux)

    安装zookeeper 安装jdk(此处省略) 解压tar包并配置变量环境 配置文件修改 将/usr/local/src/zookeeper-3.4.5/conf这个路径下的zoo_sample.cf ...

  10. ccf201703-2 STLlist

    题目:http://118.190.20.162/view.page?gpid=T56 问题描述 体育老师小明要将自己班上的学生按顺序排队.他首先让学生按学号从小到大的顺序排成一排,学号小的排在前面, ...