Raj
Raj

Reputation: 374

Problem with solving a program involving radians in `math` module

I found a python question and facing trouble in solving it correctly.

The question is as follows.

In this problem, you're going to use that class to calculate the net force from a list of forces.

Write a function called find_net_force. find_net_force should have one parameter: a list of instances of Force. The function should return a new instance of Force with the total net magnitude and net angle as the values for its magnitude and angle attributes.

As a reminder:

I tried using the following code to solve it and am getting a different result for the get_angle. I tried changing things with radians, degrees with no correct result.

from math import atan2, degrees, radians, sin, cos

class Force:

    def __init__(self, magnitude, angle):
        self.magnitude = magnitude
        self.angle = radians(angle)

    def get_horizontal(self):
        return self.magnitude * cos(self.angle)

    def get_vertical(self):
        return self.magnitude * sin(self.angle)

    def get_angle(self, use_degrees = True):
        if use_degrees:
            return degrees(self.angle)
        else:
            return self.angle

def find_net_force(force_instances):
    total_horizontal = 0
    total_vertical = 0
    for instance in force_instances:
        total_horizontal += float(instance.get_horizontal())
        total_vertical += float(instance.get_vertical())
    net_force = round((total_horizontal ** 2 + total_vertical ** 2) ** 0.5, 1)
    net_angle = round(atan2(total_vertical, total_horizontal), 1)
    total_force = Force(net_force, net_angle)
    return total_force

force_1 = Force(50, 90)
force_2 = Force(75, -90)
force_3 = Force(100, 0)
forces = [force_1, force_2, force_3]
net_force = find_net_force(forces)
print(net_force.magnitude)
print(net_force.get_angle())

The expected output is:

103.1
-14.0

The actual result I got is:

103.1
-0.2

Update:

Thanks to Michael O. The class was expecting degrees and the function find_net_force was sending the angle in radians. I tried using the conversion to degrees in the find_net_force and it worked.

net_angle = round(degrees(atan2(total_vertical, total_horizontal)), 1)

Upvotes: 2

Views: 1590

Answers (1)

Raj
Raj

Reputation: 374

Thanks to Michael O for helping out in the comments. The class was expecting degrees and the function find_net_force was sending the angle in radians.I tried using the conversion to degrees in the find_net_force and it worked.

net_angle = round(degrees(atan2(total_vertical, total_horizontal)), 1)

Upvotes: 1

Related Questions