首页 > 解决方案 > 解决“数学”模块中涉及弧度的程序的问题

问题描述

我发现了一个 python 问题并且在正确解决它时遇到了麻烦。

问题如下。

在这个问题中,您将使用该类从 a listof 力计算净力。

编写一个名为find_net_force. find_net_force应该有一个参数:一个list的实例Force。该函数应该返回一个新的实例Force其总净幅值和净角度作为其幅值和角度属性的值。

提醒一句:

我尝试使用以下代码来解决它,并且得到了不同的结果get_angle。我尝试用弧度、度数改变事物,但没有正确的结果。

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())

预期的输出是:

103.1
-14.0

我得到的实际结果是:

103.1
-0.2

更新:

感谢 Michael O。该类期望度数,该函数find_net_force以弧度发送角度。我尝试使用转换为度数,find_net_force它起作用了。

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

标签: pythonmath

解决方案


感谢 Michael O 在评论中提供帮助。该类期望度数,函数 find_net_force 以弧度发送角度。我尝试在 find_net_force 中使用度数转换,它起作用了。

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

推荐阅读