当前位置:   article > 正文

python interpolate_[转载]python插值

interpolate from scratch python

博主最近在学习python,结合自己专业课计算方法写下python如何做插值的3个实例。

import matplotlib.pyplot as plt

import numpy as np

#下面是numpy内置的插值函数(分段线性插值)的用法,请仔细观察学习各种画图命令

x=np.linspace(0,2*np.pi,10)

y=np.sin(x)

xvals=np.linspace(0,2*np.pi,20)

yinterp = np.interp(xvals, x, y)

plot1=plt.plot(x, y, 'o',label='original values')

plot2=plt.plot(xvals, yinterp, '-x',label='interped values')

#plot1=plt.plot(x, y, 'o',label=u'真实值')#采用unicode编码

#plot2=plt.plot(xvals, yinterp, '-x',label=u'插值')

plt.xlabel('x axis')

plt.ylabel('y axis')

plt.legend()

plt.show()

plt.savefig('c1.png')

#保存在当前目录文件夹

#自己编写的Lagrange插值函数,纯属闲着蛋疼#潘海东,2015/1/12

import matplotlib.pyplot as plt

import numpy as np

x=np.linspace(0,2*np.pi,10)

y=np.sin(x)

xvals=np.linspace(0,2*np.pi,20)

def Lagrange(x,y,x0):

n=len(x)

m=len(x0)

s=range(m)

for k in

range(m):

t=0.0

for j in range(n):

u=1.0

for i in range(n):

if i!=j:

u=u*(x0[k]-x[i])/(x[j]-x[i])

t=t+u*y[j]

s[k]=t

return

s

yinterp = Lagrange(x,y,xvals)

plot1=plt.plot(x, y, '*',label='original values')

plot2=plt.plot(xvals, yinterp, 'r',label='interped values')

plt.xlabel('x axis')

plt.ylabel('y axis')

plt.legend()

plt.show()

plt.savefig('c2.png')

#保存在当前目录文件夹

#功能超强的python插值模块interpolateimport

scipy.interpolate as itp

#导入插值库,读者可以dir(itp)查看里面有哪些插值函数

import matplotlib.pyplot as plt

import numpy as np

x=np.linspace(0,2*np.pi,10)

y=np.sin(x)

xvals=np.linspace(0,2*np.pi,20)

yinterp = itp.spline(x,y,xvals)#调用样条插值函数

plot1=plt.plot(x, y, 'b*',label='original values')

plot2=plt.plot(xvals, yinterp, 'r-x',label='interped values')

plt.xlabel('x axis')

plt.ylabel('y axis')

plt.legend()

plt.show()

plt.title('Spline')

plt.savefig('c3.png')

#保存在当前目录文件夹

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号