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)
func_x = x**2
minvalue = 1
maxvalue = 2
partitions = 100
a = riemann_sum(func_x,minvalue,maxvalue,partitions)
someList = [x**2 for x in someOtherList]
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.