Python sympy 符号 [英] Python sympy symbols

查看:27
本文介绍了Python sympy 符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用x"时和z"作为符号,我对这段代码没有问题:

When I use "x" and "z" as symbols, I have no problem with this code:

from sympy import *
x, z = symbols('x z')
y = -6*x**2 + 2*x*z**0.5 + 50*x - z
solve((diff(y, x), diff(y, z)))
y.subs({x: 5, z: 25})

但是当我使用q"时和a",解决不给我任何解决方案.

But when I use "q" and "a", solve does not give me any solution.

q, a = symbols('q a')
y = -6*q**2 + 2*q*a**0.5 + 50*q - a
solve((diff(y, q), diff(y, a)))
y.subs({q: 5, a: 25})

如您所见,我使用subs"检查目标函数中没有拼写错误.

As you can see I use "subs" to check that there is no typo in the objective function.

更新:我使用了符号"单独设置每个变量,但再次使用q"和一个"不起作用.

UPDATE: I used "Symbol" to set each variable individually, but again using "q" and "a" does not work.

# This works
x = Symbol('x')
z = Symbol('z')
y = -6*x**2 + 2*x*z**0.5 + 50*x - z
solve((diff(y, x), diff(y, z)))

# This does not work
q = Symbol('q')
a = Symbol('a')
y = -6*q**2 + 2*q*a**0.5 + 50*q-a
solve((diff(y, q), diff(y, a)))

谢谢.

推荐答案

知道了!

这完全取决于变量的字母顺序.

It all depends on an alphabetic order of your variables.

如果在第一个示例中将 x 替换为 z 并将 z 替换为 x,它也会停止工作.

If you substitute x for z and z for x in your first example it will also stop working.

Internally solve 将表达式发送到 sympy.solvers 中的函数 _solve,然后该函数尝试求解您的方程,但多次失败.

Internally solve sends the expression to the function _solve in sympy.solvers which then tries to solve your equation and fails many times.

最后作为最后的努力,它试图通过从中挑选符号来解决 -sqrt(a) + qx - sqrt(z)一个内部函数 _ok_syms,带有一个按字母顺序排序的参数(即使没有这个参数它仍然会,但如果用 reversed 包裹,它神奇地使您的示例工作在完全相反的状态方式).

Finally as a last effort what it does is it tries to solve -sqrt(a) + q or x - sqrt(z) by picking symbols from it through an internal function _ok_syms, with an argument that sorts those alphabetically (even without this argument it still would, but if wrapped with reversed it magically makes your examples works in the exactly opposite way).

所以它确实将 x - sqrt(z) 解为 x: sqrt(z)-sqrt(a) + qa: q**2.

And so it does solve x - sqrt(z) as x: sqrt(z) and -sqrt(a) + q as a: q**2.

虽然在第一种情况下它以易于解决的 50 - 10*sqrt(z) 结束,但在第二种情况下它在 -12*q + 2*sqrt 上丢失(q**2) + 50 因为它不能简化 sqrt(q**2).

While in the first case it ends up with an easily solvable 50 - 10*sqrt(z), in the second case it is lost on -12*q + 2*sqrt(q**2) + 50 as it is not able to simplify sqrt(q**2).

来源:大量测试:https://github.com/sympy/sympy/blob/master/sympy/solvers/solvers.py

这篇关于Python sympy 符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆