Skip to content

Commit

Permalink
Magnitude and Angle of Vector (TheAlgorithms#5225)
Browse files Browse the repository at this point in the history
* Magnitude and Angle 

Core function to find Magnitude and Angle of two Given Vector

* Magnitude and Angle with Doctest

added Doctest to the functions

* Update linear_algebra/src/lib.py

Co-authored-by: Christian Clauss <[email protected]>

* Update linear_algebra/src/lib.py

Co-authored-by: Christian Clauss <[email protected]>

* Changes done 

and Magnitude and Angle Issues

* black

Co-authored-by: Christian Clauss <[email protected]>
  • Loading branch information
AMANKANOJIYA and cclauss authored Oct 12, 2021
1 parent 9586a6a commit 1b0ac73
Showing 1 changed file with 30 additions and 0 deletions.
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

0 comments on commit 1b0ac73

Please sign in to comment.