python 积分 symbols_Python sympy symbols

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})

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})

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

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

Thank you.

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

Got it!

It all depends on an alphabetic order of your variables.

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

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

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

And so it does solve x - sqrt(z) as x: sqrt(z) and -sqrt(a) + q as a: 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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值