Ryan Franz - 1 year ago 61

Python Question

Sorry if this is a easy question, or if it has already been answered, but I'm new to programming and I couldn't find a helpful answer to this question (maybe I don't know some terms that would've helped my search).

How can I include a mathematical function as an argument of a function in python?

In my particular case, I'm writing a Riemann sum calculator that would ideally look like:

`def riemann_sum(func_x, minvalue, maxvalue, partitions)`

...

return riemannSum

where func_x is some function of x so that I could find the riemann sum of any arbitrary function this:

`func_x = x**2`

minvalue = 1

maxvalue = 2

partitions = 100

a = riemann_sum(func_x,minvalue,maxvalue,partitions)

print(a)

However, I can't do the above procedure because x is undefined.

I can get the Riemann sum for particular functions of x by manually typing it in to a line of my function that looks like:

`someList = [x**2 for x in someOtherList]`

Here, the function is x**2, but I can't change it without physically going in and changing the function.

My only solution right now is to define a new Riemann sum function every time I want to find the definite integral of a new function... which works but I feel like there's a better way.

(Edit: My question is different from the Riemann sum question marked as a possible duplicate. Their question is about an implementation specifically for a Riemann sum. My question is about how to incorporate a math function as the argument of a function, and I happen to use Riemann sum as a particular example)

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

In Python functions are first class objects so you can, for example, pass functions as arguments to other functions. That is, the way you wrote your `riemann_sum`

function declaration is fine.

What doesn't work is your definition of `func_x`

, since you need to define `func_x`

as a function. For that you can either do:

```
func_x = lambda x: x**2
```

or, for a more general multiline (or single line) function

```
def func_x(x):
temp = x**2 # just to stretch this out to another line for demonstration
return temp
```

Then you can say something like:

```
def riemann_sum(func_x, minvalue, maxvalue, partitions):
# below just demos calling func_x, and is a bad way to do the sum
riemannSum = 0
step = 1.0*(maxvalue-minvalue)/partitions
value = minvalue
while value<maxvalue:
riemannSum == step*func_x(value) # here's where func_x is called
return riemannSum
```

That is, the main point here is that is demonstrates how to call `func_x`

within the `riemann_sum`

function. This allows you to evaluate `func_x`

at different x-values, as required to evaluate the sum.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**