I want to solve the equation in python:
x+conj(x)=2
x-conj(x)=4
Then, ovbiously x is 1+2i.
In python, I am using sympy and lumpy package like this.
BUT! there is no outcome. just blanket came up.
What should I do to solve these equations in python?
You really can't mix numpy and sympy expressions. Numpy doesn't understand sympy's functions nor symbols, and vice versa sympy doesn't understand about unevaluated numpy functions.
Therefore, you need to write everything with sympy functions.
Note that your system of equations doesn't have a solution. For example in the second equation (x-conj(x)) gives 4i for x=1+2i.
Unfortunately, sympy doesn't work very well with this type of equations. A straightforward way to write them, would be:
from sympy import symbols, Eq, conjugate, solve, I, re, im
x = symbols('x')
solve([Eq(x + conjugate(x), 2), Eq(x - conjugate(x), 4*I)])
which wrongly gives no solution.
Some experimenting does give a way to write the equations and get the expected outcome:
xc = re(x) - I * im(x)
solve([Eq(x + xc, 2), Eq(x - xc, 4 * I)])
Output: [{x: 1 + 2*I, re(x): 1, im(x): 2}]
Related
Is there any way in Sympy to rewrite equations for only one of the variables. Consider the following code:
>>> from sympy import symbols, sin, cos, exp, I
>>> phi, theta = symbols(["phi", "theta"])
>>> expr = (I*sin(phi) - cos(phi)) * sin(2*theta)
>>> expr.rewrite(exp) # this rewrites both theta and phi in terms of exp
I*(exp(2*I*theta) - exp(-2*I*theta))*exp(-I*phi)/2
>>> expr.simplify() # this does not simplify to exp since the exponent is -ix
(I*sin(phi) - cos(phi))*sin(2*theta)
What I require instead is:
sin(2*theta)*exp(-I*phi)
So, is there any way to tell Sympy that it should rewrite in terms of exp for only the variable phi, and not theta. I could use replace to achive this, but is there a "hands-free" to achieve this?
I think replace is the solution here. And it's not so much the theta or phi as much as it is the fact that the sum is written as the trig expansion of exp. So let's target sums in the (factored) expression:
>>> expr.replace(lambda x:x.is_Add, lambda x:x.rewrite(exp))
-exp(-I*phi)*sin(2*theta)
Experienced with Python. New to Sympy.
I have a transcendental equation, f(x) = sin(x) - x.
If y = f(x), I want to solve for x knowing y.
I think Sympy can do this, but I have no experience with it. Can someone explain what I should do?
(The question Transcendental Equation has answers for hand-rolling the iterative approach, which is my back-up.)
Here is what I have tried:
from sympy import *
x = symbols('x')
solve(Eq(sin(x) - x)) # Exception raised here
# NotImplementedError: multiple generators [x, sin(x)]
# No algorithms are implemented to solve equation -x + sin(x)
I recognize this does not even communicate that I have a known value for y. As you can see, I don't understand what to do at all.
This would be an iterative solution. Is there a way to get sympy to do this, or should I be using a different Python package for iterative solutions?
All help is appreciated.
What about using nsolve? ie:
>>> from sympy import *
>>> x = symbols('x')
>>> nsolve(sin(x)-x, x, 1)
It seems it uses mpmath.findroot behind the curtains.
I'm reading an article about Bloom filters, https://en.wikipedia.org/wiki/Bloom_filter, in which an expression is derived for the optimal number of hash functions. I'd like to reproduce the computation for the simplified case that m = n, that is, I'd like to determine the minimum of the function
(1-exp(-x))**x
which, from the article, should occur at x = ln(2). I tried doing this with sympy as follows:
In [1]: from sympy import *
In [2]: x, y, z = symbols('x y z')
In [3]: init_printing(use_unicode=True)
In [8]: from sympy.solvers import solve
In [9]: solve(diff((1-exp(-x))**x,x), x)
However, I get a
NotImplementedError: multiple generators [x, exp(x), log(1 - exp(-x))]
No algorithms are implemented to solve equation x*exp(-x)/(1 - exp(-x)) + log(1 - exp(-x))
I would just like to double-check whether Sympy really cannot solve this problem? Perhaps I need to add additional constraints/assumptions on x?
When you run into this issue where an equation can't be solved by manipulation of symbols (solving analytically), it's possible that it can still be solved by trying different numbers and getting to (or very close to) the correct answer (solving numerically).
You can convert your sympy solution to a numpy-based function, and use scipy to solve numerically.
from sympy import lambdify
from scipy.optimize import fsolve
func_np = sp.lambdify(x, diff((1-exp(-x))**x,x), modules=['numpy'])
solution = fsolve(func_np, 0.5)
This solves the equation as 0.69314718, which is what you expect.
A game I played has a riddle that involves solving the following equation:
x*411 + y*295 + z*161 = 3200
Not wanting to think I just slapped it into sympy, which I haven’t really used up to that point:
>>> from sympy import *
>>> x, y, z = symbols('x y z', integer=True, positive=True)
>>> solve(x*411 + y*295 + z*161 - 3200, [x, y, z])
[{x: -295*y/411 - 161*z/411 + 3200/411}]
Hmm, this only gave me a dependent solution, but I want all possible solutions in the domain I constrained the variables to, e.g. (assuming there are no other solutions) [{x: 4, y: 2, z:6}] or [(4, 2, 6)]
Of course I could now manually substitute two variables in a nested loop, or solve it by hand (as I did to get the solution above), but I want to know how to get sympy (or another library) to do it for me.
SymPy can solve Diophantine equations but doesn't have a built-in way to generate positive solutions. With Sage one can do that easily: here is four-line code that generates all nonnegative integer solutions of your equation.
p = MixedIntegerLinearProgram()
w = p.new_variable(integer=True, nonnegative=True)
p.add_constraint(411*w[0] + 295*w[1] + 161*w[2] == 3200)
p.polyhedron().integral_points()
The output is ((4, 2, 6),)
Behind the scenes, integral_points will most likely just run a multiple loop; although when that doesn't seem to work it tries to use Smith normal form.
I know you wanted positive solutions, but (a) it's easy to exclude any zero-containing tuples from the answer; (b) it's also easy to replace x by x-1, etc, prior to solving; (c) sticking to "nonnegative" makes it easy to create a polyhedron using Mixed Integer Linear Programming module
as above.
According to documentation one can also build a Polyhedron object directly from a system of inequalities ("Hrep"). This would allow one to explicitly say x >= 1, etc, but I haven't succeeded at this route.
With SymPy
The output of SymPy's Diophantine module is a parametric solution, like
(t_0, 2627*t_0 + 161*t_1 - 19200, -4816*t_0 - 295*t_1 + 35200)
in your example. This can be used in a loop to generate solutions in a pretty efficient way. The sticky point is finding bounds for parameters t_0 and t_1. Since this is just an illustration, I looked at the last expression above and plugged the limits 35200/4816 and 35200/295 directly in the loops below.
from sympy import *
x, y, z = symbols('x y z')
[s] = diophantine(x*411 + y*295 + z*161 - 3200)
print(s)
t_0, t_1 = s[2].free_symbols
for t0 in range(int(35200/4816)+1):
for t1 in range(int(35200/295)+1):
sol = [expr.subs({t_0: t0, t_1: t1}) for expr in s]
if min(sol) > 0:
print(sol)
The output is [4, 2, 6].
I am trying to use sympy to solve an equation for a one dimensional steady state model of the solar wind. I have the code below
from sympy import Eq, var, solve
var('r',real=True)
eq = Eq((1./2.)*((CF**2)/(r))+CT*r**(gamma)+bm/(2.*muo) - CM)
a = solve(eq,r)
Where CF, CT, CM, gamma, muo, and bm are just real numbers. I am trying to solve the equation for r over a range of values for bm but it will not return any numbers. Upon running the block of code, my python notebook just displays that the code is running but doesnt return a value nor does it stop. Is there an alternative function or some sort of command I should be giving to sympy in order to make it work faster?
The equation involves the sum of two powers of r, including r**gamma. Unless gamma is a very small integer (between -4 and 4), there is no hope of solving this symbolically (which is what sympy is for).
To solve it numerically, you need scipy rather than sympy. For example:
from scipy.optimize import fsolve
func = lambda r : (1./2.)*((CF**2)/(r))+CT*r**(gamma)+bm/(2.*muo) - CM
# assign some numeric values to CF, CT, gamma, bm, muo, CM
sol = fsolve(func, 1) # 1 is the initial guess for the solver