如何在 python 中定义一个函数,该函数将作为输入 mathematica 函数及其参数并应用于它。

How to define a function in python that takes as an input mathematica function and it's argument and apply to it.

我想定义一个将参数作为数学函数的函数,它的参数和迭代次数(我正在使用不动点定理寻找函数的零点)。 我知道如何寻找零点,但我不知道如何让我的数学方程从函数本身获取参数。

def f(function,x,iterations)

当我尝试像这样调用函数时:

f(x**2+3,-1,20)

该函数使用 x 的现有变量(我已经为另一个代码和平定义)而不是我在这里寻找的 x=-1。 我要找的结果是 +4

我该如何解决这个问题?我试图在我的函数中定义另一个函数,但我被明确要求为我的函数提供这三个参数。

感谢您的帮助。

将您的函数存储到一个字符串中,这样 'x**2' 然后在您的函数内部使用 eval 方法来使用该函数。评估()

在python中,函数本身首先是class对象,可以作为参数传递。可以在外面定义基函数。

def my_f(x):
    return x**2+3

def my_functor(f, x, iterations):
    for i in xrange(iterations):
        x = f(x)
    return x

print my_functor(my_f, -1, 20)

也许您可以找到一种更隐式的方式来使用装饰器来定义相同的仿函数。

def iterated(fn):
    """
    A decorator to make a function iterate over its outputs.
    """
    def iterated_func(*args, **kwargs):
        x = args[0]
        iterations = args[1]
        for i in xrange(iterations):
            x = fn(x)
        return x
    return iterated_func

@iterated
def my_g(x):
    return x**2+3

在这种情况下,my_g(3,1)==my_f(3) 将计算为 True。也就是说,通过在您定义的函数上添加装饰器 @iterated,您可以更改其行为以获取迭代次数作为参数。

您可以使用 sympy 安全地评估数学表达式。

首先,安装sympy:

pip install sympy

那么,你可以这样起诉:

import sympy as sy

def mathfunc(formula, **kwargs):
    expr = sy.sympify(formula)
    return expr.evalf(subs=kwargs)


mathfunc(formula="x**2+3", x=-1, iterations=20)

您可以像这样将其转换为 int

>>> int(myformula(formula="x**2+3", x=-1, iterations=20))
4

或在 mathfuncreturn 语句上添加 int()

请注意,我没有使用 iterations,因为你没有提到你想用它做什么,但你可以在 mathfunc 中随意使用它。