Python:接受三个参数的部分
Python: partial that takes three arguments
我正在尝试通过阅读本书 Data Science from Scratch by Joel Grus 来学习 Python,在第 94 页上,他们描述了如何使用以下代码[=16] 来逼近 f = x^2 的导数=]
def difference_quotient(f, x, h):
return (f(x + h) - f(x)) / h
def square(x):
return x * x
def derivative(x):
return 2 * x
derivative_estimate = partial(difference_quotient, square, h=0.00001)
# plot to show they're basically the same
import matplotlib.pyplot as plt
x = range(-10,10)
plt.title("Actual Derivatives vs. Estimates")
plt.plot(x, map(derivative, x), 'rx', label='Actual')
plt.plot(x, map(derivative_estimate, x), 'b+', label='Estimate')
plt.legend(loc=9)
plt.show()
一切正常,但是当我将行 derivative_estimate = partial(difference_quotient, square, h=0.00001)
更改为 derivative_estimate = partial(difference_quotient, f=square, h=0.00001)
时(因为我认为这样更容易阅读),然后出现以下错误
Traceback (most recent call last):
File "page_93.py", line 37, in <module>
plt.plot(x, map(derivative_estimate, x), 'b+', label='Estimate')
TypeError: difference_quotient() got multiple values for keyword argument 'f'
这是怎么回事?
在这个话题中得到了解答和完美解释:
- functools.partial wants to use a positional argument as a keyword argument
在您的情况下,这意味着您应该将 x
作为 关键字参数传递 :
plt.plot(x, [derivative_estimate(x=item) for item in x], 'b+', label='Estimate')
我正在尝试通过阅读本书 Data Science from Scratch by Joel Grus 来学习 Python,在第 94 页上,他们描述了如何使用以下代码[=16] 来逼近 f = x^2 的导数=]
def difference_quotient(f, x, h):
return (f(x + h) - f(x)) / h
def square(x):
return x * x
def derivative(x):
return 2 * x
derivative_estimate = partial(difference_quotient, square, h=0.00001)
# plot to show they're basically the same
import matplotlib.pyplot as plt
x = range(-10,10)
plt.title("Actual Derivatives vs. Estimates")
plt.plot(x, map(derivative, x), 'rx', label='Actual')
plt.plot(x, map(derivative_estimate, x), 'b+', label='Estimate')
plt.legend(loc=9)
plt.show()
一切正常,但是当我将行 derivative_estimate = partial(difference_quotient, square, h=0.00001)
更改为 derivative_estimate = partial(difference_quotient, f=square, h=0.00001)
时(因为我认为这样更容易阅读),然后出现以下错误
Traceback (most recent call last):
File "page_93.py", line 37, in <module>
plt.plot(x, map(derivative_estimate, x), 'b+', label='Estimate')
TypeError: difference_quotient() got multiple values for keyword argument 'f'
这是怎么回事?
在这个话题中得到了解答和完美解释:
- functools.partial wants to use a positional argument as a keyword argument
在您的情况下,这意味着您应该将 x
作为 关键字参数传递 :
plt.plot(x, [derivative_estimate(x=item) for item in x], 'b+', label='Estimate')