Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve sin(z)=2 in Sympy?

Sympy works with complex numbers, therefore there is possibility to solve equations like sin(z)=2. However, I cannot work it out. Anyone has an idea how to solve it in Sympy?

BTW, the solution has form like following:

z=\frac{\pi}{2}+\ln(2\pm\sqrt{3})i

<code>z=\frac{\pi}{2}+\ln(2\pm\sqrt{3})i</code>

I will add a very specialized method to solve this problem in Sympy, which can hardly be genralized:

from sympy import *
z=symbols('z')
r=re(sin(z)-2)
i=im(sin(z))
x,y=symbols('x,y',real=True)
eq1=r.subs({re(z):x,im(z):y})
eq2=i.subs({re(z):x,im(z):y})
solve((eq1,eq2),(x,y))

The output is [(pi/2, log(-sqrt(3) + 2)), (pi/2, log(sqrt(3) + 2))]. Anyone has a better solution?

like image 784
Kattern Avatar asked Feb 14 '23 01:02

Kattern


2 Answers

If you prefer the log format, use .rewrite(log), like

In [4]: asin(2).rewrite(log)
Out[4]:
      ⎛  ___        ⎞
-ⅈ⋅log⎝╲╱ 3 ⋅ⅈ + 2⋅ⅈ⎠

Combining this with Games's answer, you can get:

In [3]: sols = solve(sin(z) - 2, z)

In [4]: sols
Out[4]: [π - asin(2), asin(2)]

In [5]: [i.rewrite(log) for i in sols]
Out[5]:
⎡         ⎛  ___        ⎞        ⎛  ___        ⎞⎤
⎣π + ⅈ⋅log⎝╲╱ 3 ⋅ⅈ + 2⋅ⅈ⎠, -ⅈ⋅log⎝╲╱ 3 ⋅ⅈ + 2⋅ⅈ⎠⎦

And by the way, there are really infinitely many solutions, because sin is 2*pi periodic. SymPy currently doesn't support giving all of them directly, but it's easy enough to get them by using sin(z + 2*pi*n) instead of sin(z):

In [8]: n = Symbol('n', integer=True)

In [9]: sols = solve(sin(z + 2*pi*n) - 2, z)

In [10]: sols
Out[10]: [-2⋅π⋅n + asin(2), -2⋅π⋅n + π - asin(2)]

In [11]: [i.rewrite(log) for i in sols]
Out[11]:
⎡              ⎛  ___        ⎞                    ⎛  ___        ⎞⎤
⎣-2⋅π⋅n - ⅈ⋅log⎝╲╱ 3 ⋅ⅈ + 2⋅ⅈ⎠, -2⋅π⋅n + π + ⅈ⋅log⎝╲╱ 3 ⋅ⅈ + 2⋅ⅈ⎠⎦

Here n is any integer.

like image 129
asmeurer Avatar answered Feb 27 '23 00:02

asmeurer


Well you need to set it like this

sin(z) - 2 = 0

So like this:

>>> from sympy.solvers import solve
>>> from sympy import *
>>> z = Symbol('z')
>>> solve(sin(z) - 2, z)
[pi - asin(2), asin(2)]
>>> asin(2).evalf()
1.5707963267949 - 1.31695789692482*I
like image 32
Games Brainiac Avatar answered Feb 27 '23 00:02

Games Brainiac