1

我遇到了以下问题,首先我将简要解释发生了什么:

f(x)
g(x, y) = f(x) - y

从那里我们期望

g(x, f(x)) = f(x) - f(x) = 0

lambdified g(x,y)返回非常接近零而不是零的东西。这是重现问题的代码。只有当我进行足够数量的log评估时它才会到达f(x)

要点:https ://gist.github.com/marekyg​​gdrasil/39a24213ebaba6293464d116821cc334

来源:

from sympy import Symbol, pprint, log, lambdify

# setting symbols
g1 = Symbol("gamma1")
g2 = Symbol("gamma2")
g3 = Symbol("gamma3")
g4 = Symbol("gamma4")
rt = Symbol("rt")

# setting expressions
criteria  = (g1 * log(g1, 2.0))/2.0
criteria += (g2 * log(g2, 2.0))/2.0
criteria += (g3 * log(g3, 2.0))/2.0
criteria += (g4 * log(g4, 2.0))/2.0
rooteq = criteria - rt

print "\ncriteria function: "
pprint(criteria)

print "\ncriteria function - rt: "
pprint(rooteq)

# lambdifying expressions to callable functions
tsymbols = [g1, g2, g3, g4, rt]
lambfun_criteria = lambdify(tsymbols, criteria)
lambfun_rooteq = lambdify(tsymbols, rooteq)

# example point x
x = [0.25006462253641376, 2.2501938662000542, 2.2501938662000542, 2.2501938662000542, 0.0]

# evaluating of criteria on x
rootval = lambfun_criteria(*x)

# setting rt to this evaluation
x[4] = rootval

print "\nactual evaluation of rooteq: " + str(lambfun_rooteq(*x))
print "\nexpected evaluation of rooteq: " + str(- x[4] + lambfun_criteria(*x))

输出

$ python lambdifytest.py 

criteria function: 
0.721347520444482⋅γ₁⋅log(γ₁) + 0.721347520444482⋅γ₂⋅log(γ₂) + 0.721347520444482⋅γ₃⋅log(γ₃) + 0.721347520444482⋅γ₄⋅log(γ₄)

criteria function - rt: 
0.721347520444482⋅γ₁⋅log(γ₁) + 0.721347520444482⋅γ₂⋅log(γ₂) + 0.721347520444482⋅γ₃⋅log(γ₃) + 0.721347520444482⋅γ₄⋅log(γ₄) - rt

actual evaluation of rooteq: 4.4408920985e-16

expected evaluation of rooteq: 0.0
4

1 回答 1

0

SymPy我发现当表达式被lambdified时可以指定一个自定义数学模块。在我的情况下mpmath帮助。

导入mpmath并将精度设置为您认为足够的东西

from mpmath import mp
mp.dps = 15

告诉 SymPy 你希望你的 lambda 函数mpmath用于处理浮点运算

lambfun_criteria = lambdify(tsymbols, criteria, "mpmath")
lambfun_rooteq = lambdify(tsymbols, rooteq, "mpmath")

最后我得到了输出

actual evaluation of rooteq: 0.0
expected evaluation of rooteq: 0.0

问题的原因如下,创建的 lambda 函数中使用的默认浮点运算与比较结果的脚本中使用的不同。

如果有人需要复制粘贴,我用完整的解决方案文件更新了要点

https://gist.github.com/marekyg​​gdrasil/39a24213ebaba6293464d116821cc334#file-lambdify_test_solution-py

编辑:忘记提供文档参考

http://docs.sympy.org/dev/modules/utilities/lambdify.html

于 2017-01-23T22:31:25.490 回答