在Python中求解非线性方程的动态数量

在Python中求解非线性方程的动态数量

本文介绍了在Python中求解非线性方程的动态数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Fsolve似乎是正确的选择,我只需要帮助动态传递方程式即可.我先感谢您的任何想法.

Fsolve in Scipy seems to be the right candidate for this, I just need help passing equations dynamically. I appreciate any thoughts in advance.

通过动态,我的意思是方程的数量在一次运行中与另一次运行不同,例如,我遇到的一种情况:

By dynamic I mean number of equations differ from one run to another for example one situation i have :

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是变量.

alpha, beta, A, B, C, D and E are all constants. x, y, z, w are variables.

推荐答案

我还没有使用Fsolve自己,但是根据其文档,它需要一个可调用的函数.这样的事情可以处理具有未知数量变量的多个函数.请记住,必须在此处正确地排列args,但是每个函数只需要一个列表.

I haven't used Fsolve myself, but according to its documentation it takes a callable function.Something like this handles multiple functions with unknown number of variables. Bear in mind that the args must be ordered correctly here, but each function simply takes a list.

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,您可以尝试以下操作(未经测试):

For Fsolve, you could try something like this (untested):

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, ...)

这篇关于在Python中求解非线性方程的动态数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:37