Skip to content

Instantly share code, notes, and snippets.

@aaronjeline
Last active September 9, 2016 20:14
Show Gist options
  • Save aaronjeline/7ef592e88c961fb289d69b0996bdced7 to your computer and use it in GitHub Desktop.
Save aaronjeline/7ef592e88c961fb289d69b0996bdced7 to your computer and use it in GitHub Desktop.
#Run in sageMath https://sagecell.sagemath.org/
import numpy as np
from math import sqrt
#Return the dot product of v & w
def dotProduct(v,w):
return sum(map(lambda x, y: x*y, v, w))
#Return the norm of vector v
def norm(v):
return sqrt(dotProduct(v,v))
#Returns a unit vector with the same direction as vector v
def getUnitVector(v):
length = norm(v)
return map(lambda x: x/length, v)
#Returns a list of n random unit vectors
def randomVector(n,vectors=[]):
if n == 0:
return vectors
else:
#generating normalized random unit vectors
theta = 2 * np.pi * np.random.random()
phi = np.pi * np.random.random()
vectors.append(vector([np.cos(theta) * np.sin(phi), np.sin(theta) * np.sin(phi), np.cos(phi)]))
return randomVector(n-1, vectors)
u = randomVector(1)[0]
U = randomVector(100)
products = list(map(lambda x: abs(dotProduct(x, u)), U))
plotList = zip(U, map(lambda x: x*255, products))
avgDotProduct = sum(products)/len(products)
plots = list(map(lambda x: plot(x[0], color=(x[1],x[1],x[1])), plotList))
plots.append(plot(u, color='red'))
show(sum(plots))
print('Average dot product: ' + str(avgDotProduct))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment