vector2.py

Created by asness

Created on February 27, 2019

1.53 KB


from vector1 import AC, r, reduce

'''revised 190227'''
'''vector operations'''

'''zero vector'''
O = [0, 0, 0]

'''basis vectors'''
I = [1, 0, 0]
J = [0, 1, 0]
K = [0, 0, 1]


def va(a, b):
    '''vector addition'''
    return [a_i + b_i for (a_i, b_i) in zip(a, b)]

def vs(aList):
    '''vector sum: add together a list of vectors'''
    return reduce(va, aList)

def vm(a, n):
    '''multiplication of vector a by scalar n'''
    return [n * i for i in a]

def vdist(a, b):
    '''distance from a to b, i.e. b - a'''
    return va(b, vm(a, -1))

def u(a):
    '''unit vector'''
    return vm(a, 1.0/r(a))

def md2v(m, d):
    '''magnitude (m) and direction (d) to vector'''
    return vm(u(d), m)

def cp(a, b):
    '''cross product'''
    if len(a) == 2:
        return a[0]*b[1] - a[1]*b[0]
    if len(a) == 3:
        return [a[1]*b[2] - a[2]*b[1],
                a[2]*b[0] - a[0]*b[2],
                a[0]*b[1] - a[1]*b[0]]

def dp(a, b):
    '''dot product'''
    return sum([i * j for (i, j) in zip(a, b)])

def stp(a, b, c):
    '''scalar triple product'''
    return dp(a, cp(b, c))

def ang(a, b):
    '''angle between a and b'''
    return AC(dp(a, b) / (r(a) * r(b)))

def axangs(a):
    '''angles between vector a and each axis'''
    return [ang(a, i) for i in (I, J, K)]

def comp(a, b):
    '''scalar projection of a onto b'''
    return dp(a, u(b))

def proj(a, b):
    '''vector projection of a onto b'''
    return vm(u(b), comp(a, b))

def orth(a, b):
    '''proj(a, b) + orth(a, b) == a'''
    return vdist(proj(a, b), a)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.