Last active
January 20, 2016 22:36
-
-
Save clbarnes/1b935f03270e286bc0d8 to your computer and use it in GitHub Desktop.
Do you have a multivariate function which you want to integrate? Do you have a blasé attitude towards executing lambdas instantiated from eval strings? Well then look no further!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from inspect import signature | |
from scipy.integrate import quad | |
def get_fn_str(fn, lims=(0, 1), existing_string=None, arg_count=0): | |
""" | |
Recursively generate a string which, when evaluated, will integrate an arbitrary function over all of its variables within the given limits. | |
""" | |
if existing_string is None: | |
return get_fn_str(fn, lims=lims, existing_string="quad({{}}, {}, {})[0]".format(lims[0], lims[1]), | |
arg_count=arg_count+1) | |
param_list = list(signature(fn).parameters) | |
reached_depth = arg_count == len(param_list) - 1 | |
modified_string = existing_string.format( | |
"lambda {}: quad({}, {}, {}{})[0]".format( | |
', '.join(param_list[-arg_count:]), | |
fn.__name__ if reached_depth else '{}', | |
lims[0], | |
lims[1], | |
list_to_tuple_str(param_list[-arg_count:]) | |
) | |
) | |
if reached_depth: | |
return modified_string | |
else: | |
return get_fn_str(fn, lims=lims, existing_string=modified_string, arg_count=arg_count+1) | |
def integrate(fn, lims=(0, 1)): | |
""" | |
Integrate an arbitrary function over all of its variables within the given limits. | |
""" | |
return eval(get_fn_str(fn)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment