I want to write a function in python that has as two arguments, the sine and the cosine of an angle and it returns the angle. Which formula do we use to calculate the angle knowing the sine and the cosine? If we could just use the inverse trigonometric functions we wouldn't have to define two arguments for the function. I don't have an idea how we can calculate the angle. Can you help please?
Programming-how to find the angle
578 Views Asked by Bumbble Comm https://math.techqa.club/user/bumbble-comm/detail AtThere are 4 best solutions below
On
If you are not able to use any inverse function, given the sine and the cosine of an angle, you can compute the tangent of the angle:
$$\tan{\theta} = \frac{\sin{\theta}}{\cos{\theta}}$$
And then, compute the $\arctan$ using the power series:
$$\arctan{x} = x - \frac{x^3}{3} + \frac{x^5}{5} - \frac{x^7}{7} + \frac{x^9}{9} - ...$$ or $$\arctan{x} = \sum_{n=0}^{\infty}(-1)^n\cdot\frac{x^{2n+1}}{2n+1}$$
In python code it would be something like this:
def get_angle(sinx, cosx):
tanx = sinx / cosx
arctanx = 0
# More iterations means more accuracy
for n in range(0, 20):
arctanx += ((-1)**n)*((tanx**(2*n+1)) / (2*n+1))
return arctanx
On
If math.atan2 (as mentioned in John's answer) isn't allowed, then you could use:
import cmath
def get_angle(sinx, cosx):
return cmath.log(cosx + 1j * sinx).imag
This works because Euler's formula $e^{ix} = \cos(x) + i \sin(x)$ is equivalent to $\log(\cos(x) + i \sin(x)) = ix$.
Your instructor may still consider it “an inverse function”, though.
On
A non-“cheating” approach to use if the standard math.atan2 is not allowed:
import math
def atan2(y, x):
# Use symmetry to restrict the result range to [0, pi/4]
if y < 0:
return -atan2(-y, x)
if x < 0:
return math.pi - atan2(y, -x)
if y > x:
return math.pi / 2 - atan2(x, y)
# Normalize to unit circle to give c = cos(theta), s = sin(theta)
r = math.hypot(x, y)
c = x / r
s = y / r
# Use the small-angle identity sin(theta) = theta when applicable.
if s <= 2e-8:
return s
# Otherwise, use half-angle identity
tan_half = s / (1 + c)
return 2.0 * atan2(tan_half, 1)
Note that there are no calls to trig functions nor inverse trig functions. Instead, the algorithm works by recursively bisecting the angle until the small-angle approximation can be used.
will produce the angle, where $c$ is the known cosine and $s$ is the known sine. The value produced will lie between $-\pi$ and $\pi$; if you want it to be between $-180$ degrees and $180$ degrees, use