Is there a Vector3 type in Python?
Asked Answered
H

3

7

I quickly checked numPy but it looks like it's using arrays as vectors? I am looking for a proper Vector3 type that I can instance and work on.

Hauteloire answered 24/4, 2009 at 16:46 Comment(3)
What is it you want to do that NumPy's arrays don't support?Sagacious
I want a dedicated type with instance methods.Hauteloire
Consider that using a separate object for each vector can be potentially inefficient if you are manipulating thousands of vectors at once. Matrices composed of vectors avoid this issue, also known as vectorization. What would arguably be a more useful class is a Vector class that stores many vectors and offers methods for e.g. normalizing all at once etc.Brisbane
U
5

ScientificPython has a Vector class. for example:

In [1]: from Scientific.Geometry import Vector
In [2]: v1 = Vector(1, 2, 3)
In [3]: v2 = Vector(0, 8, 2)               
In [4]: v1.cross(v2)
Out[4]: Vector(-20.000000,-2.000000,8.000000)
In [5]: v1.normal()
Out[5]: Vector(0.267261,0.534522,0.801784)
In [6]: v2.cross(v1)
Out[6]: Vector(20.000000,2.000000,-8.000000)
In [7]: v1*v2 # dot product
Out[7]: 22.0
Umont answered 24/4, 2009 at 17:44 Comment(2)
The links in your answer are 404s now.Flavorsome
It looks like ScientificPython has been abandoned.Tittup
L
2

I don't believe there is anything standard (but I could be wrong, I don't keep up with python that closely).

It's very easy to implement though, and you may want to build on top of the numpy array as a container for it anyway, which gives you lots of good (and efficient) bits and pieces.

Loathe answered 24/4, 2009 at 17:1 Comment(2)
Thanks, but would I be able to write instance methods for it? i.e. the array type lets me do this: vector.Unitize()Hauteloire
What's so special about instance methods? Or custom classes. This is Python, after all, not Java or C#. Besides, I believe Simon is recommending you extend the numpy array, which would give you instance methods, no?Dodwell
W
-1

I know the above answer was already accepted. However, if someone already has numpy installed, you can use the array class like so. It overloads the arithmetic operators allowing calculations across all values of the array sort of like a Vector.

from numpy import array

vector3a = array([1,2,3])
vector3b = array([3,2,1])
print(vector3a + vector3b)
>>> array([4, 4, 4])
Within answered 7/10, 2022 at 4:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.