在假期利用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. HDU 1711 Number Sequence 【KMP应用 求成功匹配子串的最小下标】

    传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1711 Number Sequence Time Limit: 10000/5000 MS (Java/O ...

  2. POJ 3067 Japan 【树状数组经典】

    题目链接:POJ 3067 Japan Japan Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 32076   Accep ...

  3. POJ 1632 Vase collection【状态压缩+搜索】

    题目传送门:http://poj.org/problem?id=1632 Vase collection Time Limit: 1000MS   Memory Limit: 10000K Total ...

  4. 在idea配置jetty和创建(包、文件)javaWeb以及Servlet简单实现

    在创建之前要安装好jetty jetty官网链接:https://jettylife.com/ 现在进行创建项目: 需要按照好jdk 现在进行添加jetty 现在进行配置 完成后ok ok 下面警告的 ...

  5. An Algorithm for Surface Encoding and Reconstruction From 3D Point Cloud Data

    An Algorithm for Surface Encoding and Reconstruction From 3D Point Cloud Data https://www.youtube.co ...

  6. 整理关于 VS Code 一些小技巧:系列一

    官方介绍 VisualStudioCode是一个轻量级且功能强大的源代码编辑器,它运行在桌面上,支持Windows.MacOS和Linux系统.它提供了对JavaScript.TypeScript和N ...

  7. MySQL数据库主从(主主)配置

    一.系统环境: centos7.4 (centos 1708) mysql 5.7 master主机的IP地址为192.168.159.50 slave主机的IP地址为192.168.159.51 M ...

  8. 【PTA 天梯赛训练】六度空间(广搜)

    “六度空间”理论又称作“六度分隔(Six Degrees of Separation)”理论.这个理论可以通俗地阐述为:“你和任何一个陌生人之间所间隔的人不会超过六个,也就是说,最多通过五个人你就能够 ...

  9. Django模板简介

    在settings.py中有个TEMPLATES的设置,其中BACKEND用来配置Django模板引擎, DIRS 定义了一个目录列表,模板引擎按列表顺序搜索这些目录以查找模板源文件 一般我们都会把模 ...

  10. 启用image-filter扩展模块

    进入lnmp目录打开lnmp.conf配置文件 修改Nginx_Modules_Options=' --prefix=/usr/local/nginx --with-http_image_filter ...