如何用Sympy求解一个简单的二次方程?

时间:2014-11-06 19:24:36

标签: sympy

solve(-14.4*(x**2)+71.8*x+5.083, x)

结果为无。怎么会?我的计算给出了两个根,5.0559和-0.063

2 个答案:

答案 0 :(得分:3)

也许您没有使用最新版本。我得到了

>>> from sympy import *
>>> var('x')
x
>>> solve(-14.4*(x**2)+71.8*x+5.083, x)
[-0.0698162934055920, 5.05592740451670]

答案 1 :(得分:0)

更一般地说:

import sympy as sp

y = 'a * x ** 2 + b * x + c' # for example a quadratic polynomial

s = sp.var('x a b c')        # define four symbols as variables

print(sp.solve(y,  s ))      # sympy solves y(a,b,c,x) for each of a, b, c, x
print(sp.solve(y,  x ))      # sympy solves Y(a,b,c,x) for x treating a, b, c as constants
print(sp.solve(y, 'x'))      # sympy solves Y(a,b,c,x) for x treating a, b, c as constants

产量:

[(x, -(b*x + c)/x**2, b, c)]
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]

虽然:

s = sp.var('x')              # define one symbol as a varible

print(sp.solve(y,  s ))      # sympy solves Y(a,b,c,x) for x treating a, b, c as constants
print(sp.solve(y,  x ))      # sympy solves Y(a,b,c,x) for x treating a, b, c as constants
print(sp.solve(y, 'x'))      # sympy solves Y(a,b,c,x) for x treating a, b, c as constants

返回:

[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]
[(-b + sqrt(-4*a*c + b**2))/(2*a), -(b + sqrt(-4*a*c + b**2))/(2*a)]