Tae Hyoun Park - 8 months ago 32

Python Question

In Scipy, one-dimensional integration of a function with multiple parameters is achieved by specifying the constant parameters in the function definition through the

`args`

This example is from the Scipy Reference Guide:

`>>> from scipy.integrate import quad`

>>> def integrand(x, a, b):

... return a * x + b

>>> a = 2

>>> b = 1

>>> I = quad(integrand, 0, 1, args=(a,b))

>>> I = (2.0, 2.220446049250313e-14)

https://docs.scipy.org/doc/scipy/reference/tutorial/integrate.html

I always thought that local variables defined within functions are inaccessible outside the definition. Here, this seems not true since quad only requires

`integrad`

`(x, a, b)`

`(a, b)`

What is happening here? What am I missing?

Answer

`quad`

doesn't know anything about what variables `integrand`

uses. It doesn't know that the arguments are called `a`

and `b`

. It only sees the *values* of the global variables `a`

and `b`

, and it passes those values *positionally* to the integrand. In other words, the code would work the same if you did

```
x = 2
y = 1
I = quad(integrand, 0, 1, args=(x,y))
```

`quad`

does not even know how many arguments `integrand`

accepts, other than that it accepts at least one. `quad`

passes the value of the variable of integration as the first argument. You, the user, have to know that, and pass the right number. If you don't (for instance if you didn't pass `args`

, or just passed one arg), you'll get an error. `quad`

just blindly passes along whatever arguments you give it.

Source (Stackoverflow)