【问题标题】:Problem with solving a program involving radians in `math` module解决“数学”模块中涉及弧度的程序的问题
【发布时间】:2019-05-11 04:30:25
【问题描述】:

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

问题如下。

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

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

提醒一下:

  • 要找到合力的大小,请将所有水平分量相加,并将所有垂直分量相加。净力是水平力和垂直力平方和的平方根(即(total_horizontal<sup>2</sup> + total_vertical<sup>2</sup>)<sup>0.5</sup>
  • 要找到合力的角度,请使用两个参数调用atan2:总垂直力和总水平力(按此顺序)。请记住将大小和方向四舍五入到小数点后一位。这可以使用 round(magnitude, 1) 和 round(angle, 1) 来完成。
  • Force 类具有三个方法:get_horizontal 返回单个力的水平分量。 get_vertical 返回单个力的垂直分量。 get_angle 返回单个力的角度,以度为单位(如果您调用 get_angle(use_degrees=False),则以弧度为单位。
  • 提示:不要过于复杂。除了 atan2degrees 和 radians 之外,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)

【问题讨论】:

  • 在这一行中:total_force = Force(net_force, net_angle) net_angle 是弧度,但 Force 类是用度数初始化的
  • 在您的代码中,您似乎是以弧度为单位舍入一个角度,然后以度为单位输出它,并希望它正确到 1 d.p。但是 0.1 弧度大约是 6 度。我建议只在显示/输出之前四舍五入,以避免复合错误。
  • @MichaelO。我很早就想到了,但我在课堂上改变了一些没有用的东西。现在我尝试在函数中使用转换,它起作用了。非常感谢。

标签: python math


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-06-25
    • 2019-03-21
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2011-02-17
    • 2011-03-03
    相关资源
    最近更新 更多