Home > Back-end >  how can I improve this if else statement?
how can I improve this if else statement?

Time:10-09

for finding the direction of ray in cartesian plane

def direction(self):
        if 180>self.angle>90:
            return (-1, 1)
        elif 90>self.angle>0:
            return (1,1)
        elif 0>self.angle>-90:
            return (1,-1)
        elif -90>self.angle>-180:
            return (-1,-1)

this looks kinda bulky is there a simpler way out? it simply will give me the angle of ray and I want to see in which quadrant the ray is going

CodePudding user response:

Looks fine to me, You can replace the last elif with an else instead like this

def direction(self):
        if 180>self.angle>90:
            return (-1, 1)
        elif 90>self.angle>0:
            return (1,1)
        elif 0>self.angle>-90:
            return (1,-1)
        else:
            return (-1,-1)

CodePudding user response:

You don't need a conditional statement at all if you use math.copysign and the fundamental trig functions:

from math import copysign, sin, cos, pi

def direction(angle):
    angle *= pi / 180
    return copysign(1, cos(angle)), copysign(1, sin(angle))
  • Related