作为练习,我编写了一个脚本,该脚本为函数function oddOneOut(arr) {
let word = ''
if (arr[0] === arr[1]) {
word = arr[0]
}
if (arr[1] === arr[2]) {
word = arr[1]
}
if (arr[2] === arr[3]) {
word = arr[2]
}
function wrong(element) {
return element !== word
}
return arr.findIndex(wrong)
}
console.log(oddOneOut(["sword", "sword", "sword", "sword", "drows", "sword"]))
//returns 4
(此处为n
(此处为1)生成度x0
(此处为8)的泰勒多项式的系数,f(x)
(此处为1)。 sqrt(x)^ sqrt(x))。
我使用了for循环将这种近似转换为独立函数T(x)
。然后,我使用Ts(x)
定义了scipy.interpolate.approximate_taylor_polynomial
。通过测试0到1之间的值,我确定了SciPy函数的scale
参数的最佳值约为0.3(您不能超过1,因为该函数未定义为负x)。
正如我预期的那样,我的函数T(x)
的性能明显比Ts(x)
差,如下面的图所示,从x = 0到3:
我不是做什么的SciPy?
我想知道答案是否可能与SciPy dx
函数中的derivative
参数有关。我选择了e1-2,因为较高的值会产生nans,而较低的值会产生明显的废话。我也对order
参数进行了估算:错误消息告诉我它必须是大于n的奇数值,所以我在for循环中使用了2*i+1
。
这是我的完整代码。
# Imports
import numpy as np
from scipy.interpolate import approximate_taylor_polynomial
from scipy.misc import derivative
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline
# Function I'm trying to approximate
def f(x):
return np.sqrt(x) ** np.sqrt(x)
degree=8 # I am making an 8th degree polynomial
x0=1 # Centered about x=1
dvs=[f(x0)] # This will hold the values of the nth degree derivative
coef=[f(x0)] # And this will hold the polynomial coefs (dvs divided by the corresponding factorials)
for i in range(1,degree+1):
# I'm not entirely sure what the dx parameter does here, but 1e-2 produced the most accurate results.
a = derivative(f,x0=x0,dx=1e-2,n=i,order=2*i+1) # Compute the derivative
dvs.append(a) # Append to dvs
coef.append(a/np.math.factorial(i)) # Compute the coefficient and append to coef
# Pretty pandas dataframe
out=pd.DataFrame({"degree":range(0,degree+1),"value":dvs,"coef":coef})
# Define Taylor polynomial using my coefs
def T(x):
r = 0
for i in range(0,degree+1):
r = r + out['coef'][i] * ((x - x0) ** i)
return r
# Use the scipy function for comparison. It is a poly1d object which can behave like a function.
# Not shown: I tried scale values on np.linspace(0,1,101) and 0.3 was about the best.
Ts = approximate_taylor_polynomial(f,x=x0,degree=8,scale=0.3)
# Test x values to display our functions
x = np.linspace(0,3,301)
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
# Actual function
ax.plot(x,f(x),c="black",label="f(x)")
# My approximation
ax.plot(x,T(x),c="deepskyblue",label="T(x)")
# Scipy approximation
# Note that scipy doesn't account for the horizontal translation
ax.plot(x,Ts(x-x0),c="forestgreen",label="Ts(x) (scale 0.3)")
ax.legend()
这将输出上面显示的图形。
如何提高我的近似度?