我正在寻找 Python 中非常快速的插值方法。以下是我的代码:
计算时间也会减少,但是我没有太多降低输入数据点数的可能性。
from scipy.integrate import quad
import numpy as np
from scipy import interpolate
import time
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
input="-0.5 0.0 \
-0.4 0.6 \
-0.3 0.9 \
-0.2 0.85 \
-0.1 0.82 \
0.0 0.8 \
0.1 0.7 \
0.2 0.6 \
0.3 0.4 \
0.4 0.3 \
0.5 0.02"
start_time = time.time()
input_coordinates = np.genfromtxt(input.splitlines()).reshape(-1,2) # shape to 2 columns, any number of rows
x_coordinates = input_coordinates[:,0]
H_values = input_coordinates[:,1]
H_interpolation = interpolate.InterpolatedUnivariateSpline(x_coordinates, H_values)
# H_interpolation = interp1d(x_coordinates, H_values)
# H_interpolation = interp1d(x_coordinates, H_values, kind='cubic')
def function(x):
return H_interpolation(x)*np.exp(2/np.sqrt(1+x))
complex_integral = quad(function, -0.5, 0.5)
print("Quad",complex_integral)
print("--- %s seconds ---" % (time.time() - start_time))
xnew = np.arange(-0.5, 0.5, 0.01)
ynew = H_interpolation(xnew) # use interpolation function returned by `interp1d`
plt.plot(x_coordinates, H_values, '.', label='original data')
plt.plot(xnew, ynew, '-', label='interpolation')
plt.legend()
plt.show()
用途:
interpolate.InterpolatedUnivariateSpline
时间为0.011002779006958008秒 而对于:
interp1d type linear
时间为0.05301189422607422秒 并且针对:
interp1d type cubic
时间为0.03500699996948242秒。
但我正在寻找一些更快的东西,因为在大循环中有多个计算。在Python中是否有任何更快的函数近似?它还应该是准确的。
我观察到,如果我减少输入点的数量
input
计算时间也会减少,但是我没有太多降低输入数据点数的可能性。
quad
内的插值。这将会多次调用插值函数(至少21次?),每次只传入一个值。你可能想尝试其他积分方法,寻找一种能够让你少次调用插值函数,但每次传入多个点的方法。这样可能会更快。 - undefinedH_interpolation(x)
?当我在def function(x)
中打印时,方程式中的H_interpolation(x)
部分会导致额外的计算,可能是不必要的。 - undefinedynew = function(xnew);simps(ynew,xnew)
这样做速度更快,但根据输入可能不够准确。另一种可能性是实现一个低级可调用函数,这样做速度也更快,并且得到相同的结果。但这需要更多的工作(包装/重新实现评估样条的Fortran代码,并创建一个低级可调用函数,然后将其传递给scipy.integrate.quad)。 - undefined