I'm trying to solve an equation in python using SymPy. I have a generated equation (something like function = y(8.0-(y**3.0)) which I use with SymPy to create a new equation like this: eq = sympy.Eq(function, 2) which outputs y(8.0-(y**3.0)) == 2. but sympy.solve(eq) doesn't seem to work.
>>> from sympy import Eq, Symbol as sym, solve
>>> y = sym('y')
>>> eqa = Eq(y(8.0-(y**3.0)), 8)
>>> solve(eqa)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.6/sympy/solvers/solvers.py", line 332, in solve
result = tsolve(f, *symbols)
File "/usr/lib/pymodules/python2.6/sympy/solvers/solvers.py", line 716, in tsolve
raise NotImplementedError("Unable to solve the equation.")
NotImplementedError: Unable to solve the equation.
thanks for reading.
Yours is a non linear equation ... So you can use optimize.fsolve for it. For further details look for the function in this tutorial scipy
(I don't know why you mention scipy in your question when you use sympy in your code. I'll assume you are using sympy.)
Sympy can solve this equation if you specify an integer power for y (ie y**3.0 changed to y**3).
The following works for me using Sympy 0.6.7.
from sympy import Eq, Symbol, solve
y = Symbol('y')
eqn = Eq(y*(8.0 - y**3), 8.0)
print solve(eqn)
Assuming you mean you were trying to use sympy, as opposed to scipy, then you can get Sympy (works with v0.7.2+) to solve it by making a small adjustment to way you defined your equation - you just need to put a multiplication operator (*) in between the first 'y' and the '('. It doesn't appear to matter whether you specify the power as a float or not (but it's possible it was required in 0.6.7).
from sympy import Eq, var, solve
var('y')
eq = Eq(y*(8.0-(y**3.0)), 8)
solve(eq)
For nonlinear equations, you should use sympy.solvers.nsolve to solve it numerically, except for some special cases where a more specific and appropriate solver may exist (e.g. tsolve).
For example, the following script should output 1.2667664310254.
from sympy import Symbol
from sympy.solvers import nsolve
from sympy import sin, tan
theta = Symbol('theta')
print nsolve(tan(theta)/(1+1*sin(theta)) - 4.0**2/9.81, theta, (1.2,))
This is a non-linear equation. What you need to look for is a root finding algorithm in SciPy.
Related
I am Currently working on some optimization problem which involves non-linear constraint. The problem is as follows :
I need to perform either of the two minimizations shown in image in python. I found library scipy which has optimize.minimize() function but I am unable to fit in the Non-Linear constraint using scipy.NonLinearConstraint. Can anyone guide? How to solve this? Is there also a way to solve it using some homotopy function given in any of the libraries? I have tried (adding constraint for the alternative one)as:
con = lambda A,x,y : np.matmul(A,x) - y
nlc = NonlinearConstraint(con, 0, epsilon)
So, I finally could solve the above optimization by using spgl1 solver in python. It can be used as shown below:
from spgl1 import spgl1, spg_bp, spg_bpdn
#x01 = psueodinverse of A multiplied by y
x,resid,grad,info = spgl1(A, y, tau = tau, sigma = epsilon, x0 = x01, iter_lim = 150)
one can refer about the above solver at github link or pypi link
I am working with complex functions in sympy (python 3) and am having trouble getting sympy to simplify the equations. In particular I can't get sympy to use Euler's Identity to break up the complex exponential into real and imaginary parts. Here is my code:
import sympy as sym
from sympy import I, init_printing
# setup printing
init_printing()
# complex potential cylinder in uniform flow
U,z,R,theta=sym.symbols('U z R theta')
F=U*z+U/z
# complex velocity cylinder in uniform flow
compVel=sym.diff(F,z)
exp1=sym.sympify('R*exp(I*theta)')
compVel=compVel.subs(z,exp1)
print(compVel)
phi,psi=sym.symbols('phi psi')
phi=sym.re(compVel)
psi=sym.im(compVel)
print(phi)
print(psi)
When I run this code the output is:
U - U*exp(-2*I*theta)/R**2
re(U) - re(U*exp(-2*I*theta)/R**2)
im(U) - im(U*exp(-2*I*theta)/R**2)
Am I missing something or is sympy not powerful enough to do recognize this simplification? Thanks in advance!
I figured it out; #Stelios is correct but in addition when you use sympify you must pass a dictionary with the local variables that the expression contains.
exp1=sym.sympify('R*exp(I*theta)',locals={'R':R,'theta':theta})
I am new to sympy and still naive about python.... I wanted to solve a trigonometric equation, to find its zeroes. (Once I have syntax, then I will use a more complex function.)
I cannot find the right syntax yet. Here is what I tried at the iPython console in Spyder (Python 2.7):
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
solve(sin(x), x)
I got this error:
Traceback (most recent call last):
File "", line 1, in
solve(sin(x), x)
NameError: name 'sin' is not defined
OK, so I need to have the correct reference to the sine function.
According to the sympy documentation, I thought this was in mpath, but this did not work:
from mpmath import *
Traceback (most recent call last):
File "<ipython-input-7-8dcdd12d9679>", line 1, in <module>
from mpmath import *
ImportError: No module named mpmath
How do I load/access mpmath or some other way to get the sine function?
This fixed it:
from sympy import sin
To access mpmath do this
from sympy.mpmath import *
I have Python 3.3.3 and SymPy 0.7.4.1, both in x64 version and installed locally on my computer. I am using PSPad as a configured editor for Python scripting.
When using imports from library sympy in a module which should solve a set of three linear equations:
from sympy import Matrix, solve_linear_system
from sympy.abc import x, y, z
def main():
system = Matrix (((3,2,-1,1) ,(2,-2,4,-2),(-1,0.5,-1,0)))
print(solve_linear_system(system, x, y,z))
if __name__ == "__main__":
main()
The editor PSPad console output returns the following:
traceback (most recent call last): File "C:\Users\GOODLU~1\AppData\Local\Temp\PSpad\securesafety_DISK_5GB\Programmation\linear system solve SYMPY.py", line 1, in <module>
from sympy import Matrix,solve_linear_system File "C:\Users\GOODLU~1\AppData\Local\Temp\PSpad\securesafety_DISK_5GB\Programmation\sympy.py", line 2, in <module>
from sympy import var,Eq,solve ImportError: cannot import name var
Process completed, Exit Code 1.
Execution time: 00:00.134
Actually, I am wondering myself heavily about those issues:
Why, when typing the same thing, without an object def main(), and entered line by line in IDLE, everything is solved correctly, as: {x: 1.00000000000000, y: -2.00000000000000, z: -2.00000000000000}
Why, my PSPad file with object, having the same computation lines, doesn't work and returns errors?
In fact, I would like to use SymPy in normal python code and get computed results in a list or printed in console( .. as in IDLE). Just in order to avoid some annoying line-to-line IDLE manipulations, what should my code file look like?
The problem seems to be that you have created a file named sympy.py, which has the same name as the sympy module.
Hence, in the from sympy import ... statement, your sympy.py is acting as the sympy module.
Try renaming the file to something else, like sympy_programming_test.py and let know if it works.
When I run this program, I get no solution at the end, but there should be a solution ( I believe). Any idea what I am doing wrong? If you take away the Q from e2 equation it seems to work correctly.
#!/usr/bin/python
from sympy import *
a,b,w,r = symbols('a b w r',real=True,positive=True)
L,K,Q = symbols('L K Q',real=True,positive=True)
e1=K
e2=(K*Q/2)**(a)
print solve(e1-e2,K)
It works if we do the following:
Set Q=1 or,
Change e2 to e2=(K*a)(Q/2)**(a)
I would still like it to work in the original way though, as my equations are more complicated than this.
This is just a deficiency of solve. solve is based mostly on heuristics, so sometimes it isn't able to figure out how to solve an equation when it's given in a particular form. The workaround here is to just call expand_power_base on the expression, since SymPy is able to solve K - K**a*(Q/2)**a:
In [8]: print(solve(expand_power_base(e1-e2),K))
[(2/Q)**(a/(a - 1))]
It's also worth pointing out that the result of [] from solve does not in any way mean that there are no solutions, only that solve was unable to find any. See the first note at http://docs.sympy.org/latest/tutorial/solvers.html.