简体   繁体   中英

Python solve cubic equation using sympy

I am have a problem when trying to solve an equation using sympy . Some of the variables have specific values assigned. I am trying to solve the equation for b , c and d . This is my attempt:

from random import randint
import sympy
from sympy.abc import b,c,d,B,C,r,x

B=10
C=20
r=123

# Equation: x^3+b*x^2+c*x+d=x^3+(B−r)x^2+(C−B*r)x−C*r
equation = sympy.Eq(x**3+b*x**2+c*x+d,x**3+(B−r)*x**2+(C−B*r)*x−C*r)

print(sympy.solve(equation,"b"))
print(sympy.solve(equation,"c"))    
print(sympy.solve(equation,"d"))

Python prints me the following error:

    [user@user Python Scripts]$ python polygen.py 
  File "polygen.py", line 10
    equation = sympy.Eq(x**3+b*x**2+c*x+d,x**3+(B−r)*x**2+(C−B*r)*x−C*r)
                                                  ^
SyntaxError: invalid character in identifier

What am I missing?

Something is wrong with your - character. It's not a regular character for some reason and python isn't recognizing it. I replaced all your minus signs with hyphens on my machine and it works:

from random import randint
import sympy
from sympy.abc import b,c,d,B,C,r,x

B=10
C=20
r=123

# Equation: x^3+b*x^2+c*x+d=x^3+(B−r)x^2+(C−B*r)x−C*r
equation = sympy.Eq(x**3+b*x**2+c*x+d,x**3+(B-r)*x**2+(C-B*r)*x-C*r)

print(sympy.solve(equation,"b"))
print(sympy.solve(equation,"c"))
print(sympy.solve(equation,"d"))

I'm not sure what kind of character the wrong - sign is:

a = 2−2 does not work in my machine

a = 2-2 does however

- IS a MINUS IS NOT. in Python interprets them differently, the first one encodes to u"\-" but the second encodes to u"\−" and clearly they won't do the same thing. To be sure use your numeric keyboard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM