girlygirl
girlygirl

Reputation: 11

How to find numerical intersections of two graphs, SYMPY

i'm stuck with some problem, i think it's an easy one, but i really don't know what to do. I got two functions:

f = (1+1/4)*sp.cos(t)+(1/4)*sp.cos((4-1)*t)

g = (1+1/4)*sp.sin(t)-(1/4)*sp.sin((4-1)*t)

I needed to plot them, using lambdify, i got something that looked like a rhombus. But now i needed to search the intersections of that figure with the unit circle, and i really don't know how to do that. The equation for the unit circle is: x^2+y^2=1 (i don't know any other formula for this) and i just wouldn't know how to use these equations to find the intersections.

I tried something with Nsolve but it came back as an error...

Upvotes: 0

Views: 1205

Answers (1)

JohanC
JohanC

Reputation: 80329

A unit circle can be represented either as an equation x²+y²=1, or as a parametric equation: x=cos(u); y=sin(u).

I tried a few ways to solve the combined equations, but only the following seems to work. Substituting the equations for f and g into the circle equation and then call sympy's standard solve. This gives 4 solutions, as to be expected from the plot.

As explained in sympy's gotchas, Python converts the fraction 1/4 to the float 0.25 before sympy gets the chance to represent it as a proper fraction. When floats are encountered, many of sympy's symbolic operations start working with numeric approximations. This can be avoided using the S operator on the nominator or the denominator, converting the fraction to a sympy fraction.

Sympy's plot_parametric can plot the rhomboic curve and plot_implicit can draw the circle equation.

from sympy import symbols, Eq, pi, cos, sin, solve, plot_parametric, plot_implicit, S

t, x, y = symbols('t x y')
f = (1 + S(1) / 4) * cos(t) + (S(1) / 4) * cos((4 - 1) * t)
g = (1 + S(1) / 4) * sin(t) - (S(1) / 4) * sin((4 - 1) * t)
circle = Eq(x ** 2 + y ** 2, 1)
sol = solve([circle.subs({x: f, y: g})], t)
print(sol)
print([s.evalf() for s, in sol])

p1 = plot_parametric(f, g, (t, 0, 2 * pi), line_color='b', show=False)
p2 = plot_implicit(circle, line_color='r', show=False)
p1.append(p2[0])
p1.show()

Solution for t: -3/4 π, -1/4 π, 1/4 π and 3/4 π.

Numeric:[-2.35619449019234, -0.785398163397448, 0.785398163397448, 2.35619449019234]

resulting plot

Upvotes: 4

Related Questions