fender
fender

Reputation: 11

How to solve for unknown theta angle

So I am trying to write a script that solves for an unknown angle. The equation will be of the form of:

P*sin(theta)+Q*cos(theta)=G

Where P, Q, and G are known values and theta needs to be found. I was wondering if there was a way to do this with numpy or math modules. I am really new to python so trying to figure out what modules are out there and how to use them.

From googling around I heard about fsolve but unsure how to use it. Is there a library for solving for unknowns?

Upvotes: 1

Views: 115

Answers (2)

lastchance
lastchance

Reputation: 6480

OK, as requested. The aim is to write the LHS as A.sin(theta+phi). Then we would be able to solve from

sin(theta+phi)=G/A

or

theta=asin(G/A)-phi          ( exists provided abs(G) <= abs(A) )

So you need to find A and phi such that

P.sin(theta)+Q.cos(theta) = A.sin(theta+phi)
                          = A[ sin(theta)cos(phi)+cos(theta)sin(phi) ]

Equate coefficients of cos(theta) and sin(theta):

A.sin(phi)=Q,     A.cos(phi)=P

Square and add:

A2=P2+Q2

Divide:

tan(phi)=Q/P     ( phi=atan2(Q,P) gives correct quadrant )

In code, with a check:

import math

def get_theta( P, Q, G ):
    ''' Returns (one value of) theta such that P.sin(theta) + Q.cos(theta) = G'''
    return math.asin( G / math.sqrt( P ** 2 + Q ** 2 ) ) - math.atan2( Q, P )

P, Q, G = 4, 3, 2
theta = get_theta( P, Q, G )
print( "theta = ", theta, " radians, or ", theta * 180 / math.pi, "degrees" )
print( "Check: LHS = ", P * math.sin( theta ) + Q * math.cos( theta ) )

Output:

theta =  -0.2319842627257963  radians, or  -13.291719167642189 degrees
Check: LHS =  2.0000000000000004

Important notes:

(1) It is your responsibility to check there IS a solution ( sqrt(P2+Q2)>=abs(G) )

(2) If there is one solution then there are an infinity of others; n.pi+(-1)nasin(G/A)-phi

Upvotes: 2

Amir H. Rassafi
Amir H. Rassafi

Reputation: 36

Have you tried to use Scipy?

import numpy as np
from scipy.optimize import fsolve

#Define P, Q, G
def equation(theta):
    return P * np.sin(theta) + Q * np.cos(theta) - G

result = fsolve(equation, 0)
print(result)

Upvotes: 0

Related Questions