简体   繁体   English

用户定义的函数可以调用吗?

[英]Are user defined functions callable?

I am not a very experience programmer. 我不是一个非常有经验的程序员。 Please can you tell me why this code gives me the error message: 请您告诉我为什么此代码会给我错误消息:

error: quad: first argument is not callable 错误:四元组:第一个参数不可调用

code: 码:

from matplotlib import pyplot as plt
import numpy as np
import scipy.integrate as integrate

def parabola(x, a):
    return a+x**2

x=np.arange(-10, 10, 1)

plt.plot(x, parabola(x,2))

plt.show()

int1=integrate.quad(parabola(x,2), -5, 5)
print int1

Should all user defined functions be callable? 所有用户定义的函数都可以调用吗?

There are two problems in your code: 您的代码中有两个问题:

1) you call the function parabola() . 1)调用函数parabola() Instead, pass it as an argument to integrate . 而是将其作为integrate的参数传递。

2) parabola() is a two argument function. 2) parabola()是两个参数的函数。 integrate expects a single-argument function. integrate期望单参数函数。

To solve the second problem, you need to convert the two-argument function to a single-argument function. 要解决第二个问题,您需要将双参数函数转换为单参数函数。 This is a general technique known as partial application of functions. 这是一种通用技术,称为功能的部分应用

Try this: 尝试这个:

def parabola1(x): return parabola(x, 2)

int1 = integrate.quad(parabola1, -5, 5)
print int1

Try: 尝试:

int1=integrate.quad(parabola, -5, 5, args=(2,))

The quad signature is: quad签名是:

quad(func, a, b, args=(), ...)

the function, lower range, upper range, args_to_pass through, etc. 函数,下限范围,上限范围,args_to_pass传递等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM