gpt4 book ai didi

python - 矢量加法不能正常工作

转载 作者:行者123 更新时间:2023-11-28 18:34:31 25 4
gpt4 key购买 nike

我在 python 中创建了一个类,用于向量和向量加法;然而,它似乎并没有产生我预期的结果。

方向为 pi(弧度)或 180(度)且大小为 1 的向量加上方向为 pi*2(弧度)或 0/360(度)且大小为 1 的向量应使(0, 0) 的向量,对吗?但是,我从代码中得到了奇怪的结果。

(-1.5707963267948966, 1.2246467991473532e-16)

这是我从上面描述的向量加法中得到的结果。

这是我的代码:

import math

class Vector:
def __init__(self, direction, magnitude, directionType="degrees"):
if directionType=="degrees":
direction = math.radians(direction)
self.direction = direction
self.magnitude = magnitude

def __add__(self, other):
x = (math.sin(self.direction) * self.magnitude) + (math.sin(other.direction) * other.magnitude)
y = (math.cos(self.direction) * self.magnitude) + (math.cos(other.direction) * other.magnitude)
magnitude = math.hypot(x, y)
direction = 0.5 * math.pi - math.atan2(y, x)
return (direction, magnitude)



v1 = Vector(math.pi, 1, directionType="radians")
v2 = Vector(math.pi*2, 1, directionType="radians")

print v1+v2

最佳答案

1.22e-16 是一个很小的数字。如果您不喜欢看到它,请将您的数字四舍五入到合理的精度,它将为零。我不希望角度是可预测的,在这种情况下它似乎是 pi/2。四舍五入到小数点后 10 位的示例:

angle, magnitude= v1+v2
magnitude = round(magnitude, 10)
result = (angle, magnitude)
print(result)

关于python - 矢量加法不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com