Lou De Jesus
Lou De Jesus

Reputation: 1

Problems solving nonlinear systems of equations involving trig functions in Python using Sympy

I'm trying to create a program that solves the solutions for an equation of a circle:

equation

This is the code I wrote for it using Sympy. It works for functions like x^2, but I always encounter an error when using tan(x) or sin(x)

import sympy as sym

x = sym.symbols('x')
y = sym.symbols('y')
f = sym.Eq(sym.sqrt(9-x**2), y)
g = sym.Eq(sym.tan(x), y)
print(sym.solve((f, g)(x, y)))

Graphical solutions show that a solution definitely exists.

Upvotes: 0

Views: 45

Answers (1)

Davide_sd
Davide_sd

Reputation: 13185

Just because plots show a solution, it doesn't mean that the solution can be computed analytically. solve is used to get an analytical solution. We can use nsolve to compute a numerical solution, but we are going to find suitable initial conditions, hence a plot is more than welcome.

from sympy import *
var("x, y")
eq1 = Eq(y, sqrt(9 - x**2))
eq2 = Eq(y, tan(x))
plot(eq1.rhs, eq2.rhs, (x, -pi, pi), ylim=(-5, 5))

enter image description here

The plot shows that there are 3 solutions in the interval [-pi, pi]. Read help(nsolve) to get acquainted with its syntax. To find the solutions we will have to play with initial guesses:

s1 = nsolve([eq1, eq2], [x, y], [-2, 2])
s2 = nsolve([eq1, eq2], [x, y], [1, 2])
s3 = nsolve([eq1, eq2], [x, y], [-2.9, 0.5])
print(s1)
print(s2)
print(s3)
# out
# Matrix([[-1.98982600933056], [2.24512637786642]])
# Matrix([[1.22089272895276], [2.74033226897584]])
# Matrix([[-2.99643622736316], [0.146184593393441]])

You can verify graphically that the solutions are correct.

Upvotes: 3

Related Questions