vendredi 21 avril 2017

Implementing 3D vectors in Python: numpy vs x,y,z fields

I am implementing a 3D Vector class in Python. My vector has coordinates x, y and z (all floats), and I need to decide how to store this information. I can see at least three options here:

1) Make three separate float fields: self.x, self.y, self.z

class Vector:

  def __init__(self, x, y, z):
    self.x = x
    self.y = y
    self.z = z

2) Make a list, say, with three elements. I may also use a tuple if the objects can be constant.

class Vector:

  def __init__(self, x, y, z): = [x,y,z]

3) Make a numpy array, say, with three elements.

import numpy as np    

class Vector:

  def __init__(self, x, y, z): = np.array([x,y,z])

For options (2) and (3), I could then implement properties and setters to access the single coordinates

def x(self):

4) Why not having some redundancy? I could have both a list (or tuple, or numpy array) and separate fields x, y and z.

The class is meant to be used to perform common operations such as vector addition, inner product, cross product, rotation, etc. Performance of these operations needs to be taken into account.

Is there a solution that I should prefer, and why?


0 commentaires:

Enregistrer un commentaire