python - 解决“数学”模块中涉及弧度的程序的问题
问题描述
我发现了一个 python 问题并且在正确解决它时遇到了麻烦。
问题如下。
在这个问题中,您将使用该类从 a list
of 力计算净力。
编写一个名为find_net_force
. find_net_force
应该有一个参数:一个list
的实例Force
。该函数应该返回一个新的实例Force
其总净幅值和净角度作为其幅值和角度属性的值。
提醒一句:
- 要找到合力的大小,请将所有水平分量相加,并将所有垂直分量相加。净力是水平力和垂直力平方和的平方根(即)
(total_horizontal2 + total_vertical2)0.5
- 要找到合力的角度,请调用
atan2
使用两个参数调用:总垂直力和总水平力(按此顺序)。请记住将大小和方向四舍五入到小数点后一位。这可以使用round(magnitude, 1) 和round(angle, 1) 来完成。 - 该类
Force
具有三个方法:get_horizontal
返回单个力的水平分量。get_vertical
返回单个力的垂直分量。get_angle
返回以度为单位的单个力的角度(如果您调用,则以弧度为单位get_angle(use_degrees=False)
. - 提示:不要过度复杂化。Force 类有很多功能,除了
atan2
、degree
s 和radians
.
我尝试使用以下代码来解决它,并且得到了不同的结果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)
解决方案
感谢 Michael O 在评论中提供帮助。该类期望度数,函数 find_net_force 以弧度发送角度。我尝试在 find_net_force 中使用度数转换,它起作用了。
net_angle = round(degrees(atan2(total_vertical, total_horizontal)), 1)
推荐阅读
- delphi - 在 Delphi 中使用 UDP 服务器
- typescript - 类型“字符串”不能用于索引类型“通用对象”
- python - IndexError:目标 11 超出范围。交叉熵
- python - 我在这里没有看到我的错误 - 尝试学习 Python
- javascript - 如何收集用户提交的照片?
- javascript - chart.js how to make x-axis labels position top
- r - 如何在闪亮中循环观察事件?单击多边形时更改传单中的样式
- c# - 提升表单事件
- c++ - 目标函数 CPLEX C++ 中的 CEIL
- python - 无法删除列表中的所有最大元素