Skip to content

Magnitude and Angle of Vector #5225

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Oct 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions linear_algebra/src/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,36 @@ def __mul__(self, other: float | Vector) -> float | Vector:
else: # error case
raise Exception("invalid operand!")

def magnitude(self) -> float:
"""
Magnitude of a Vector

>>> Vector([2, 3, 4]).magnitude()
5.385164807134504

"""
return sum([i ** 2 for i in self.__components]) ** (1 / 2)

def angle(self, other: Vector, deg: bool = False) -> float:
"""
find angle between two Vector (self, Vector)

>>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]))
1.4906464636572374
>>> Vector([3, 4, -1]).angle(Vector([2, -1, 1]), deg = True)
85.40775111366095
>>> Vector([3, 4, -1]).angle(Vector([2, -1]))
Traceback (most recent call last):
...
Exception: invalid operand!
"""
num = self * other
den = self.magnitude() * other.magnitude()
if deg:
return math.degrees(math.acos(num / den))
else:
return math.acos(num / den)

def copy(self) -> Vector:
"""
copies this vector and returns it.
Expand Down