2017-03-15 107 views
1

我想用nsolve作为后备,以solve,并喜欢用dict = True使solve回报与发现的解决方案和相应的变量的字典。但是,nsolve似乎没有此选项。SymPy:如何使`nsolve`返回一个字典,找到的解决方案

这是我使用的是什么样的解决方法:

from sympy import * 

def nsolve(equations, variables, guesses, **flags): 
    from sympy import nsolve as originalnsolve 
    result = originalnsolve(equations, variables, guesses, **flags) 
    if "dict" in flags and flags["dict"]: 
     return [dict(zip(variables, [float(value) for value in result]))] 
    else: 
     return result 

x, y = symbols("x y") 
equations = [Eq(2*x+y, 3), Eq(y-x, 1)] 
variables = [x, y] 
guesses = [1, 1] 

print("solve with dict = True produces:\n%s\n" % solve(equations, variables, dict = True) + "The result is a dictionary, as needed\n") 
print("nsolve without dict = True produces:\n%s\n" % nsolve(equations, variables, guesses) + "nsolve doesn't return a dictionary\n") 
print("nsolve with dict = True produces:\n%s\n" % nsolve(equations, variables, guesses, dict = True) + "My workaround wrapper function returns a dictionary\n") 

输出将是:

solve with dict = True produces: 
[{x: 2/3, y: 5/3}] 
The result is a dictionary, as needed 

nsolve without dict = True produces: 
[0.666666666666667] 
[ 1.66666666666667] 
nsolve doesn't return a dictionary 

nsolve with dict = True produces: 
[{x: 0.6666666666666666, y: 1.6666666666666667}] 
My workaround wrapper function returns a dictionary 

我的问题:

  • 我错过了一个简单的方法来让nsolve返回一个字典吗?

  • 如果不是:我的方法有问题吗?

回答

1

nsolve没有一个dict选项。如果您想申请一个,您应该在issue tracker或者实现它的拉取请求中打开一个功能请求。

+1

好的,谢谢你的回复。那么我可以尝试一下。 ;-) [#12397](https://github.com/sympy/sympy/pull/12397) – Jayjayyy

相关问题