我发现了一个python问题,在正确解决该问题时遇到了麻烦。
问题如下。
在这个问题中,您将使用该类从list
个力中计算净力。
编写一个名为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
更新:
感谢MichaelO。该类期望角度,函数find_net_force
以弧度发送角度。我尝试在find_net_force
中使用转换为度的方法,它可以正常工作。
net_angle = round(degrees(atan2(total_vertical, total_horizontal)), 1)
python大神给出的解决方案
感谢Michael O在评论中提供帮助。该类正在期望度数,并且函数find_net_force以弧度发送角度。我尝试在find_net_force中使用转换为度数的方法并成功。
net_angle = round(degrees(atan2(total_vertical, total_horizontal)), 1)
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
Python pytz时区函数返回的时区为9分钟 - python由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
如何打印浮点数的全精度[Python] - python我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…
Python:检查新文件是否在文件夹中[重复] - pythonThis question already has answers here: How do I watch a file for changes? (23个答案) 3年前关闭。 我是python的新手,但是我尝试创建一个自动化过程,其中我的代码将侦听目录中的新文件条目。例如,某人可以手动将zip文件复制到一个特定的文件夹中,并且我希望我的代码能够在文件完全…