python中的class vector3D成员函数

时间:2015-04-13 14:51:33

标签: python

我正在尝试运行我的程序而且我的数字出错了。我认为它与我的vector3D成员函数有关:mag(),cos_theta(),phi(),...所以这是我的代码,这就是问的问题。 mag()返回矢量幅度,cos_theta()返回矢量与z轴的角度的cos,phi()返回xy平面中的投影角度,然后 add (), sub ()很有说服力。我只是觉得我没有为mag(),cos_theta()或phi()中的一个或多个返回正确的函数。

class Vector3D(Vector2D):
        def __int__ self, aX, aY, aZ):
                self.setX(aX)
                self.setY(aY)
                self.setZ(aZ)

        def setX(self, aX):
                self.__iX = aX

        def setY(self, aY):
                self.__iY = aY

        def setZ(self, aZ):
                self.__iZ = aZ

        def x(self):
                return self.__iX

        def y(self):
                return self.__iY

        def z(self):
                return self.__iZ


        def __add__(self, other):
                return Vector3D(self.x() + other.x(), self.y() + other.y(), self.z() + other.z())

        def __sub__(self, other):
                return Vector3D(self.x() - other.x(), self.y() - other.y(), self.z() - other.z())

        def __mul__(self, other):
                return Vector3D(self.x() * other.x(), self.y() * other.y(), self.z() * other.z())

        def __truediv__(self, other):
                return Vector3D(self.x() / other.x(), self.y() / other.y(), self.z() / other.z())

        def mag(self):
                return sqrt(self.x()**2 + self.y()**2 + self.z()**2)

        def cos_theta(self):
                return arccos(self.z())

        def phi(self):
                return arctan(self.x()/self.y())

        def print(self):
                print("The vector(x,y,z) is ", self.x(), ",", self.y(), ",", self.z(), ")

1 个答案:

答案 0 :(得分:0)

试试这个:

将其导入文件: from math import sqrt, asin

这里将运行代码(有一些输出来帮助查看答案):

class Vector3D:
    def __init__(self, x, y, z):
        self._x = x
        self._y = y
        self._z = z
    def __mul__(self, other):
        return Vector3D(self._x*other._x, self._y*other._y, self._z*other._z)
    def mag(self):
        return sqrt((self._x)^2 + (self._y)^2 + (self._z)^2)
    def dot(self, other):
        temp = self * other
        return temp._x + temp._y + temp._z
    def cos_theta(self):
        #vector's cos(angle) with the z-axis
        return self.dot(Vector3D(0,0,1)) / self.mag() #(0,0,1) is the z-axis unit vector
    def phi(self):
        #vector's 
        return asin( self.dot(Vector3D(0,0,1)) / self.mag() )
    def __repr__(self):
        return "({x}, {y}, {z})".format(x=self._x, y=self._y, z=self._z)
if __name__ == "__main__":
    samplevector = Vector3D(1,1,1)
    print(samplevector)
    print(samplevector.mag())
    print(samplevector*Vector3D(1,1,1))
    print(samplevector.cos_theta())
    print(samplevector.phi())