Created
August 25, 2021 09:24
-
-
Save Niedzwiedzw/1ed914e352787869e866be4e7cffabb9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from dataclasses import dataclass | |
import math | |
def dbg(val): | |
print(val) | |
return val | |
def to_degrees(rad: float) -> float: | |
return (rad / math.pi) * 180 | |
def from_degrees(deg: float) -> float: | |
return deg / 180 * math.pi | |
@dataclass | |
class Vec: | |
x: float | |
y: float | |
z: float | |
def add(self, other: 'Vec') -> 'Vec': | |
return Vec(self.x + other.x, self.y + other.y, self.z + other.z) | |
def sub(self, other: 'Vec') -> 'Vec': | |
return Vec(self.x - other.x, self.y - other.y, self.z - other.z) | |
def dot(self, other: 'Vec') -> float: | |
return self.x * other.x + self.y * other.y + self.z * other.z | |
def magnitude(self) -> float: | |
return (self.x**2 + self.y**2 + self.z**2) ** (0.5) | |
def cos(self, other: 'Vec') -> float: | |
return max(min((self.dot(other)) / (self.magnitude() * other.magnitude()), 1.0), -1.0) | |
def angle(self, other: 'Vec') -> float: | |
return math.acos(dbg(self.cos(other))) | |
print('Vec(1,1,1).magnitude() == ', Vec(1,1,1).magnitude()) | |
print('Vec(3,4,0).magnitude() == ', Vec(3,4,0).magnitude()) | |
assert Vec(1,1,1).magnitude() > 1.0 | |
assert Vec(1,1,1).angle(Vec(1,1,1)) == 0 | |
assert Vec(0,1,0).angle(Vec(1,0,0)) == math.pi * 0.5, Vec(0,1,0).angle(Vec(1,0,0)) | |
print("Vec(0,1,0).angle(Vec(1,0,0)) == ", to_degrees(Vec(0,1,0).angle(Vec(1,0,0))), "degrees") | |
assert from_degrees(to_degrees(math.pi)) == math.pi, from_degrees(to_degrees(math.pi)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment