There is a Vec class we are building in Coding the Matrix. The book does not build the crucial arts of the code but expects the reader to implement vector operations using the given model. I am tempted to make modifications to the class Vec itself, but I assume there is a method to the madness, so I am trying to resist that impulse.
There is not much help out there. You would think there would be some kind of forum for Coding the Matrix.
class Vec:
"""
A vector has two fields:
D - the domain (a set)
f - a dictionary mapping (some) domain elements to field elements
elements of D not appearing in f are implicitly mapped to zero
"""
def __init__(self, labels, function):
self.D = labels
self.f = function
Testing the implementation with "python -m doctest vec.py":
**********************************************************************
File "vec.py", line 48, in vec.equal
Failed example:
Vec({'a', 'b', 'c'}, {'a': 0}) == Vec({'a', 'b', 'c'}, {})
Expected:
True
Got:
False
**********************************************************************
File "vec.py", line 50, in vec.equal
Failed example:
Vec({'a', 'b', 'c'}, {}) == Vec({'a', 'b', 'c'}, {'a': 0})
Expected:
True
Got:
False
**********************************************************************
You see, an empty dictionary, dict() is {}.
Now, inherently, {'a':0'} does not equal {}, but somehow I am going to have to make Vec(D, {}) a zero vector where all values for each domain member is 0.
I found someone on the Internet who must also be going through Coding the Matrix, because the code he references is the exact same Vec class.
class Vec:
"""
A vector has two fields:
D - the domain (a set)
f - a dictionary mapping (some) domain elements to field elements
elements of D not appearing in f are implicitly mapped to zero
"""
def __init__(self, labels, function):
self.D = labels
self.f = function
__getitem__ = getitem
__setitem__ = setitem
__neg__ = neg
__rmul__ = scalar_mul #if left arg of * is primitive, assume it's a scalar
def __mul__(self,other):
#If other is a vector, returns the dot product of self and other
if isinstance(other, Vec):
return dot(self,other)
else:
return NotImplemented # Will cause other.__rmul__(self) to be invoked
def __truediv__(self,other): # Scalar division
return (1/other)*self
__add__ = add
def __radd__(self, other):
"Hack to allow sum(...) to work with vectors"
if other == 0:
return self
def __sub__(a,b):
"Returns a vector which is the difference of a and b."
return a+(-b)
__eq__ = equal
def is_almost_zero(self):
s = 0
for x in self.f.values():
if isinstance(x, int) or isinstance(x, float):
s += x*x
elif isinstance(x, complex):
s += x*x.conjugate()
else: return False
return s < 1e-20
def __str__(v):
"pretty-printing"
D_list = sorted(v.D, key=repr)
numdec = 3
wd = dict([(k,(1+max(len(str(k)), len('{0:.{1}G}'.format(v[k], numdec))))) if isinstance(v[k], int) or isinstance(v[k], float) else (k,(1+max(len(str(k)), len(str(v[k]))))) for k in D_list])
s1 = ''.join(['{0:>{1}}'.format(str(k),wd[k]) for k in D_list])
s2 = ''.join(['{0:>{1}.{2}G}'.format(v[k],wd[k],numdec) if isinstance(v[k], int) or isinstance(v[k], float) else '{0:>{1}}'.format(v[k], wd[k]) for k in D_list])
return "\n" + s1 + "\n" + '-'*sum(wd.values()) +"\n" + s2
def __hash__(self):
"Here we pretend Vecs are immutable so we can form sets of them"
h = hash(frozenset(self.D))
for k,v in sorted(self.f.items(), key = lambda x:repr(x[0])):
if v != 0:
h = hash((h, hash(v)))
return h
def __repr__(self):
return "Vec(" + str(self.D) + "," + str(self.f) + ")"
def copy(self):
"Don't make a new copy of the domain D"
return Vec(self.D, self.f.copy())
See
Vector Class ProblemsThe problem is in the equal(u, v) procedure. It seems the operation overloading depends on this working properly, so I will not be able to proceed through the book until I get this Vec class working flawlessly.
This is one of the great benefits of studying outside the university setting, as I am free to put doing exercises from the main [POOLE] text on hold to put some time into learning obscure features of Python (or C++) at my leisure.