gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Define%20a%20python%20class%20called%20vec3
- User
Define%20a%20python%20class%20called%20vec3
- Assistant
Define%20a%20python%20class%20called%20vec3
Sure! Below is an example of a simple Python class named Vec3 that represents a 3-dimensional vector. The class includes methods for basic vector operations such as addition, subtraction, dot product, cross product, and magnitude calculation.
import math
class Vec3:
def __init__(self, x=0.0, y=0.0, z=0.0):
"""Initialize a Vec3 instance."""
self.x = x
self.y = y
self.z = z
def __add__(self, other):
"""Add two vectors."""
return Vec3(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
"""Subtract two vectors."""
return Vec3(self.x - other.x, self.y - other.y, self.z - other.z)
def dot(self, other):
"""Compute the dot product of two vectors."""
return self.x * other.x + self.y * other.y + self.z * other.z
def cross(self, other):
"""Compute the cross product of two vectors."""
return Vec3(
self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x
)
def magnitude(self):
"""Compute the magnitude (length) of the vector."""
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
def normalize(self):
"""Return a normalized (unit) vector."""
mag = self.magnitude()
if mag == 0:
raise ValueError("Cannot normalize a zero vector.")
return Vec3(self.x / mag, self.y / mag, self.z / mag)
def __repr__(self):
"""Return a string representation of the vector."""
return f"Vec3({self.x}, {self.y}, {self.z})"
# Example usage
if __name__ == "__main__":
v1 = Vec3(1.0, 2.0, 3.0)
v2 = Vec3(4.0, 5.0, 6.0)
print(f"v1: {v1}")
print(f"v2: {v2}")
print(f"v1 + v2: {v1 + v2}")
print(f"v1 - v2: {v1 - v2}")
print(f"Dot product: {v1.dot(v2)}")
print(f"Cross product: {v1.cross(v2)}")
print(f"Magnitude of v1: {v1.magnitude()}")
print(f"Normalized v1: {v1.normalize()}")
__init__ method initializes the vector's coordinates (x, y, z).__add__ and __sub__ methods allow for vector addition and subtraction using the + and - operators.dot method computes the dot product of two vectors.cross method computes the cross product of two vectors.magnitude method calculates the length of the vector.normalize method returns a unit vector in the same direction as the original vector.__repr__ method provides a readable string representation of the vector.You can test this class by running the provided example usage at the bottom of the code.
Not yet included in a published release.