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
返回一個字典嗎?如果不是:我的方法有問題嗎?
好的,謝謝你的回覆。那麼我可以嘗試一下。 ;-) [#12397](https://github.com/sympy/sympy/pull/12397) – Jayjayyy