mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Magnitude and Angle of Vector (#5225)
* 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 <cclauss@me.com> * Update linear_algebra/src/lib.py Co-authored-by: Christian Clauss <cclauss@me.com> * Changes done and Magnitude and Angle Issues * black Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
parent
9586a6a98e
commit
1b0ac73da2
|
@ -148,6 +148,36 @@ class 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.
|
||||
|
|
Loading…
Reference in New Issue
Block a user