矢量加法不能正常工作

2024-04-24 05:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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

Tags: selfdefpimathsin方向向量other
2条回答

它看起来工作正常。请看What Every Computer Scientist Should Know About Floating Point Arithmetic。你知道吗

我以为有一个摘要版在什么地方出版,但我找不到。你知道吗

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

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

相关问题 更多 >