Vector class in python

mcleonard / vector.py

This file contains 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

import math
class Vector ( object ):
def __init__ ( self , * args ):
«»» Create a vector, example: v = Vector(1,2) «»»
if len ( args ) == 0 : self . values = ( 0 , 0 )
else : self . values = args
def norm ( self ):
«»» Returns the norm (length, magnitude) of the vector «»»
return math . sqrt ( sum ( x * x for x in self ))
def argument ( self , radians = False ):
«»» Returns the argument of the vector, the angle clockwise from +y. In degress by default,
set radians=True to get the result in radians. This only works for 2D vectors. «»»
arg_in_rad = math . acos ( Vector ( 0 , 1 ) * self / self . norm ())
if radians :
return arg_in_rad
arg_in_deg = math . degrees ( arg_in_rad )
if self . values [ 0 ] < 0 :
return 360 — arg_in_deg
else :
return arg_in_deg
def normalize ( self ):
«»» Returns a normalized unit vector «»»
norm = self . norm ()
normed = tuple ( x / norm for x in self )
return self . __class__ ( * normed )
def rotate ( self , theta ):
«»» Rotate this vector. If passed a number, assumes this is a
2D vector and rotates by the passed value in degrees. Otherwise,
assumes the passed value is a list acting as a matrix which rotates the vector.
«»»
if isinstance ( theta , ( int , float )):
# So, if rotate is passed an int or a float.
if len ( self ) != 2 :
raise ValueError ( «Rotation axis not defined for greater than 2D vector» )
return self . _rotate2D ( theta )
matrix = theta
if not all ( len ( row ) == len ( self ) for row in matrix ) or not len ( matrix ) == len ( self ):
raise ValueError ( «Rotation matrix must be square and same dimensions as vector» )
return self . matrix_mult ( matrix )
def _rotate2D ( self , theta ):
«»» Rotate this vector by theta in degrees.
Returns a new vector.
«»»
theta = math . radians ( theta )
# Just applying the 2D rotation matrix
dc , ds = math . cos ( theta ), math . sin ( theta )
x , y = self . values
x , y = dc * x — ds * y , ds * x + dc * y
return self . __class__ ( x , y )
def matrix_mult ( self , matrix ):
«»» Multiply this vector by a matrix. Assuming matrix is a list of lists.
Example:
mat = [[1,2,3],[-1,0,1],[3,4,5]]
Vector(1,2,3).matrix_mult(mat) -> (14, 2, 26)
«»»
if not all ( len ( row ) == len ( self ) for row in matrix ):
raise ValueError ( ‘Matrix must match vector dimensions’ )
# Grab a row from the matrix, make it a Vector, take the dot product,
# and store it as the first component
product = tuple ( Vector ( * row ) * self for row in matrix )
return self . __class__ ( * product )
def inner ( self , vector ):
«»» Returns the dot product (inner product) of self and another vector
«»»
if not isinstance ( vector , Vector ):
raise ValueError ( ‘The dot product requires another vector’ )
return sum ( a * b for a , b in zip ( self , vector ))
def __mul__ ( self , other ):
«»» Returns the dot product of self and other if multiplied
by another Vector. If multiplied by an int or float,
multiplies each component by other.
«»»
if isinstance ( other , Vector ):
return self . inner ( other )
elif isinstance ( other , ( int , float )):
product = tuple ( a * other for a in self )
return self . __class__ ( * product )
else :
raise ValueError ( «Multiplication with type <> not supported» . format ( type ( other )))
def __rmul__ ( self , other ):
«»» Called if 4 * self for instance «»»
return self . __mul__ ( other )
def __truediv__ ( self , other ):
if isinstance ( other , Vector ):
divided = tuple ( self [ i ] / other [ i ] for i in range ( len ( self )))
elif isinstance ( other , ( int , float )):
divided = tuple ( a / other for a in self )
else :
raise ValueError ( «Division with type <> not supported» . format ( type ( other )))
return self . __class__ ( * divided )
def __add__ ( self , other ):
«»» Returns the vector addition of self and other «»»
if isinstance ( other , Vector ):
added = tuple ( a + b for a , b in zip ( self , other ) )
elif isinstance ( other , ( int , float )):
added = tuple ( a + other for a in self )
else :
raise ValueError ( «Addition with type <> not supported» . format ( type ( other )))
return self . __class__ ( * added )
def __radd__ ( self , other ):
«»» Called if 4 + self for instance «»»
return self . __add__ ( other )
def __sub__ ( self , other ):
«»» Returns the vector difference of self and other «»»
if isinstance ( other , Vector ):
subbed = tuple ( a — b for a , b in zip ( self , other ) )
elif isinstance ( other , ( int , float )):
subbed = tuple ( a — other for a in self )
else :
raise ValueError ( «Subtraction with type <> not supported» . format ( type ( other )))
return self . __class__ ( * subbed )
def __rsub__ ( self , other ):
«»» Called if 4 — self for instance «»»
return self . __sub__ ( other )
def __iter__ ( self ):
return self . values . __iter__ ()
def __len__ ( self ):
return len ( self . values )
def __getitem__ ( self , key ):
return self . values [ key ]
def __repr__ ( self ):
return str ( self . values )
Читайте также:  Css style centered div

Источник

Векторы в Python

В простом смысле вектор можно рассматривать, как одномерный массив. Что касается Python, вектор – это одномерный массив списков. Он занимает элементы таким же образом, как и список Python.

Давайте теперь разберемся с созданием вектора в Python.

Создание вектора

Модуль NumPy в Python используется для создания вектора. Мы используем метод numpy.array() для создания одномерного массива, то есть вектора.

Пример 1: горизонтальный вектор.

import numpy as np lst = [10,20,30,40,50] vctr = np.array(lst) vctr = np.array(lst) print("Vector created from a list:") print(vctr)
Vector created from a list: [10 20 30 40 50]

Пример 2: вертикальный вектор.

import numpy as np lst = [[2], [4], [6], [10]] vctr = np.array(lst) vctr = np.array(lst) print("Vector created from a list:") print(vctr)
Vector created from a list: [[ 2] [ 4] [ 6] [10]]

Основные операции с вектором

Создав вектор, давайте теперь выполним некоторые базовые операции с этими векторами!

Вот список основных операций, которые можно выполнять с вектором:

  • сложение;
  • вычитание;
  • умножение;
  • деление;
  • скалярное произведение и т.д.

1. Выполнение операции сложения в векторе

Ниже мы выполнили операцию сложения векторов над векторами. Операция сложения будет выполняться element-wise manner, т.е. поэлементно, и, кроме того, результирующий вектор будет иметь такую же длину, что и два аддитивных вектора.

import numpy as np lst1 = [10,20,30,40,50] lst2 = [1,2,3,4,5] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_add = vctr1+vctr2 print("Addition of two vectors: ",vctr_add)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [1 2 3 4 5] Addition of two vectors: [11 22 33 44 55]

2. Выполнение вычитания двух векторов

Аналогичным образом, при вычитании также будет применяться поэлементный метод, и в дальнейшем элементы вектора 2 будут вычитаться из вектора 1.

Давайте посмотрим на его реализацию.

import numpy as np lst1 = [10,20,30,40,50] lst2 = [1,2,3,4,5] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_sub = vctr1-vctr2 print("Subtraction of two vectors: ",vctr_sub)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [1 2 3 4 5] Subtraction of two vectors: [ 9 18 27 36 45]

3. Выполнение умножения двух векторов

При умножении вектора элементы вектора 1 умножаются на элементы вектора 2, а вектор произведения имеет ту же длину, что и векторы умножения.

Попробуем представить себе операцию умножения:

x = [10,20] и y = [1,2] — два вектора. Таким образом, вектор произведения будет v [],

v [0] = x [0] * y [0] v [1] = x [1] * y [1]

Взгляните на приведенный ниже код:

import numpy as np lst1 = [10,20,30,40,50] lst2 = [1,2,3,4,5] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_mul = vctr1*vctr2 print("Multiplication of two vectors: ",vctr_mul)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [1 2 3 4 5] Multiplication of two vectors: [ 10 40 90 160 250]

4. Выполнение операции деления

При делении результирующий вектор является значениями частного после выполнения операции деления над двумя векторами.

Для лучшего понимания рассмотрим приведенный ниже пример.

x = [10,20] и y = [1,2] – два вектора. Таким образом, результирующий вектор v будет таким:

v [0] = x [0] / y [0] v [1] = x [1] / y [1].

Давайте теперь реализуем вышеуказанную концепцию.

import numpy as np lst1 = [10,20,30,40,50] lst2 = [10,20,30,40,50] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_div = vctr1/vctr2 print("Division of two vectors: ",vctr_div)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [10 20 30 40 50] Multiplication of two vectors: [ 1 1 1 1 1 ]

5. Векторное точечное произведение

В векторном скалярном произведении мы поэлементно производим суммирование произведения двух векторов.

вектор c = x. у = (х1 * у1 + х2 * у2)

import numpy as np lst1 = [10,20,30,40,50] lst2 = [1,1,1,1,1] vctr1 = np.array(lst1) vctr2= np.array(lst2) print("Vector created from a list 1:") print(vctr1) print("Vector created from a list 2:") print(vctr2) vctr_dot = vctr1.dot(vctr2) print("Dot product of two vectors: ",vctr_dot)
Vector created from a list 1: [10 20 30 40 50] Vector created from a list 2: [1 1 1 1 1] Dot product of two vectors: 150

Источник

python vector class

Although NumPy offers a faster option, it is still instructive to code a class for vectors in pure Python. The following code defines the Vector2D class and tests it for various operations.

What is a class vector?

The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

What is def __ sub __?

__sub__ is supposed to be the magic method equivalent of — arithmetic operator, so not sure why you’re adding them. That aside, when you do p1 — p2 , it is the same as p1. __sub__(p2) . The __sub__ function is invoked on p1 , the calculation made and the new Point object returned.

How do you check if two vectors are the same in Python?

array_equal. True if two arrays have the same shape and elements, False otherwise.

What is __ add __ in Python?

Modifying the __add__ method of a Python Class

We can define the __add__ method to return a Day instance with the total number of visits and contacts: class Day(object):

What is __ cmp __ in Python?

In Python 2, __cmp__(self, other) implemented comparison between two objects, returning a negative value if self < other , positive if self >other , and zero if they were equal.

Which is better vector or ArrayList?

its performance on add and remove is better than arraylist, but worse on get and set methods. vector is similar with arraylist, but it is synchronized. arraylist is a better choice if your program is thread-safe. . vector each time doubles its array size, while arraylist grow 50% of its size each time.

What is difference between vector and list?

The elements in vector are placed in contiguous storage so that they can be accessed and traversed using iterators. Element is inserted at the end of the vector.
.
Related Articles.

Vector List
It has contiguous memory. While it has non-contiguous memory.
It is synchronized. While it is not synchronized.

Why vector is used in Java?

Java Vector Methods. It is used to append the specified element in the given vector. It is used to append all of the elements in the specified collection to the end of this Vector. . It returns true if the vector contains all of the elements in the specified collection.

Instale FreeRADIUS y Daloradius en CentOS 7 / RHEL 7

Instalar en pc

Instale FreeRADIUS y Daloradius en CentOS 7 y RHEL 7Paso 1: instale el servidor httpd y las herramientas de desarrollo. sudo yum -y groupinstall «Herr.

Una gran noticia! Pronto podrá ejecutar aplicaciones nativas de Linux en Chromebook

Linux

Los Chromebook pronto podrán ejecutar aplicaciones de Linux, comenzando con PixelbookGoogle ha anunciado que Chrome OS pronto tendrá soporte para apli.

Sin KDEing! Linux Mint está acabando con su edición KDE

Linux

Por qué Linux Mint detuvo KDE?¿Linux Mint usa KDE??¿Cuál es la versión más estable de Linux Mint??¿Cuál es mejor KDE o mate??Cómo instalar Gnome Linux.

Últimas noticias, consejos prácticos, reseñas detalladas y guías. Tenemos todo sobre el sistema operativo Linux

Источник

Оцените статью