gpt4 book ai didi

python - 没有函数形式的给定数据集的泰勒展开式

转载 作者:行者123 更新时间:2023-12-01 04:37:55 25 4
gpt4 key购买 nike

我有 (x,y) 数据集,它是连续且可微的。确切的功能形式尚不清楚。我想在某个时候泰勒展开该图。我尝试过使用 algopy/Adipy。问题是他们需要功能形式。

我附上了algopy的示例代码。

 import numpy; from numpy import sin,cos
from algopy import UTPM

def f(x):
return sin(cos(x) + sin(x))

D = 100; P = 1
x = UTPM(numpy.zeros((D,P)))
x.data[0,0] = 0.3
x.data[1,0] = 1
y = f(x)
print('coefficients of y =', y.data[:,0])

其中 D 是多项式的阶数。

我尝试使用以下内容(x1 和 y1 是一维数组):

from scipy.interpolate import interp1d
f1 = interp1d(x1, y1, kind='cubic')
def f(x):
temp1=f1(x)
return np.float64(temp1)

但是,插值似乎没有采用 UTPM 返回的 x 的数据类型。

错误消息:

Traceback (most recent call last):
File "tay.py", line 26, in <module>
y = f(x)
File "tay.py", line 15, in f
temp1=f1(x)
File "/usr/lib/python2.7/dist-packages/scipy/interpolate/polyint.py", line 54, in __call__
y = self._evaluate(x)
File "/usr/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 449, in _evaluate
y_new = self._call(self, x_new)
File "/usr/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 441, in _call_spline
return spleval(self._spline, x_new)
File "/usr/lib/python2.7/dist-packages/scipy/interpolate/interpolate.py", line 919, in spleval
res[sl] = _fitpack._bspleval(xx,xj,cvals[sl],k,deriv)
TypeError: Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'

最佳答案

我一直在寻找相同的东西,所以我实现了这个:

import numpy as np
import matplotlib.pyplot as plt
from math import factorial as f

def dxdy(x,y,order):
dy = y
for k in range(order+1):
print(k)
dx = (x[-1]-x[0])/len(x)
if k == 1:
dy = y
elif k % 2 == 0:
dy = (dy[1:]-dy[:-1])/dx
x = x[:-1]
elif k % 2 != 0:
dy = (dy[1:]-dy[:-1])/dx
x = x[1:]
return dy

def taylor(x,y,n):
a = x[int(len(x)/2)+1]
center = int(len(x)/2)+1o
#plt.plot(y)
#plt.ylim(min(y),max(y))
for k in range(n+1):
print(k)
if k == 0:
y_hat = (y[center]*((x-a)**k))/f(k)
#plt.plot(y_hat)
else:
y_hat += (dxdy(x,y,k+1)[center]*((x-a)**k))/f(k)
#plt.plot(y_hat)
#plt.plot(y)
return y_hat

points = 101
x = np.linspace(-3*np.pi,3*np.pi,points)
y = 1/(1+np.exp(-x))
y = np.cos(x)#*x#(x**4)
center = int(points/2)
for k in range(21):
y_hat = taylor(x,y,k)
plt.figure(figsize=(8,4))
plt.ylim(min(y)*1.1,max(y)*1.1)
plt.xlim(min(x),max(x))
plt.plot(x,y)
plt.plot(x,y_hat,c='red')
plt.legend(['cs(x)','taylor, k= '+str(k)],loc='upper right')
plt.title('cos(x)')
plt.savefig('cos'+str(k)+'.png')

enter image description here

关于python - 没有函数形式的给定数据集的泰勒展开式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31404844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com