【问题标题】:solving dynamic number of non-linear equations in python在python中求解非线性方程的动态数量
【发布时间】:2012-04-05 16:29:44
【问题描述】:

Scipy 中的Fsolve 似乎是合适的人选,我只需要动态传递方程的帮助。我提前感谢任何想法。

动态我的意思是方程的数量从一个运行到另一个不同,例如我有一种情况:

alpha*x + (1-alpha)*x*y - y = 0
beta*x  + (1- beta)*x*z - z = 0
A*x + B*y + C*z = D

还有另一种情况:

alpha*x + (1-alpha)*x*y - y = 0
beta*x  + (1- beta)*x*z - z = 0
gama*x  + (1 -gama)*x*w - w =0
A*x + B*y + C*z + D*w = E

alphabetaABCDE 都是常量。 xyzw 是变量。

【问题讨论】:

  • 我玩过 Scipy,但我在动态部分上并不成功。你基本上需要提前为你的方程定义函数,这不是我想要的。然后我在 R 中探索了 BBsolve。似乎解决了我所寻求的问题。

标签: python dynamic equation nonlinear-functions


【解决方案1】:

我自己没有使用过 Fsolve,但根据它的文档,它需要一个可调用函数。 像这样的东西可以处理具有未知数量变量的多个函数。请记住,此处的 args 必须正确排序,但每个函数只需要一个列表。

def f1(argList):
    x = argList[0]
    return x**2
def f2(argList):
    x = argList[0]
    y = argList[1]
    return (x+y)**2
def f3(argList):
    x = argList[0]
    return x/3

fs = [f1,f2,f3]
args = [3,5]
for f in fs:
    print f(args)

对于 Fsolve,您可以尝试这样的方法(未经测试):

def func1(argList, constList):
    x = argList[0]
    y = argList[1]
    alpha = constList[0]
    return alpha*x + (1-alpha)*x*y - y
def func2(argList, constList):
    x = argList[0]
    y = argList[1]
    z = argList[2]
    beta = constList[1]
    return beta*x  + (1- beta)*x*z - z
def func3(argList, constList):
    x = argList[0]
    w = argList[1] ## or, if you want to pass the exact same list to each function, make w argList[4]
    gamma = constList[2]
    return gama*x  + (1 -gama)*x*w - w
def func4(argList, constList):

    return A*x + B*y + C*z + D*w -E ## note that I moved E to the left hand side


functions = []
functions.append((func1, argList1, constList1, args01))
# args here can be tailored to fit your  function structure
# Just make sure to align it with the way you call your function:
# args = [argList, constLit]
# args0 can be null.
functions.append((func1, argList2, constList2, args02))
functions.append((func1, argList3, constList3, args03))
functions.append((func1, argList4, constList4, args04))

for func,argList, constList, args0 in functions: ## argList is the (Vector) variable you're solving for.
    Fsolve(func = func, x0 = ..., args = constList, ...)

【讨论】:

  • 非常感谢您的帮助和洞察力。我的一个问题是我不知道我事先有多少个方程,所以我不能真正为它们定义函数。
  • 您从哪里获得方程式列表的来源是什么?您可以动态定义它们并附加到列表中,但这将专门针对方程式源的格式进行定制
  • @pouria3 在 python 中,几乎所有事情都发生在运行时。在运行时,您应该知道您有多少股票,因为您拥有它们。您不必提前了解
  • 您好,非常感谢您的帮助和见解。我开始在 R 中探索 BBsolve。与 python 模块相比,它对我来说似乎更灵活
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-02
  • 2014-03-23
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多