Reputation: 374
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:
(total_horizontal2 + total_vertical2)0.5
)atan2
with two arguments: the total vertical and total horizontal forces (in that order). Remember to round both the magnitude and direction to one decimal place. This can be done using round(magnitude, 1) and round(angle, 1).Force
class has three methods: get_horizontal
returns a single force's horizontal component. get_vertical
returns a single force's vertical component. get_angle
returns a single force's angle in degrees (or in radians if you call get_angle(use_degrees=False)
.atan2
, degree
s, and radians
.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
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
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