def test_muldiv(self): self.assertEqual(a*b, 22.0) self.assertEqual(a*0.9, vector([1.8, 3.6, 6.3])) self.assertEqual(0.9*a, vector([1.8, 3.6, 6.3])) self.assertEqual(a/2, vector([1, 2, 3.5]))
from __init__ import vector, Q # vectors can be of any length. They must be constructed using a sequence. # For our ease, we will use 3D vectors only. a = vector([2, 4, 7]) # Data stored as float # Sequence operations print len(a) # Should give the vector dim print a[2] # Should give us the 3rd coeff print list(a) # Uses the iterator generator # Unary operations print a # Calls repr print str(a) # Same as repr print float(a) # Magnitude of vector print abs(a) # Same as float, long(a) would be same print +a # Calls pos print -a # Calls neg b = vector([3, 4, 0]) # Binary operations print b + a # Calls add print b - a # Calls sub print a * b # Calls mul, computes a dot product print a * 0.9 # Calls mul, scales the vetor print 0.9 * a # Calls rmul to override the float's mul def print a / 0.9 # Calls div print a % b # Calls mod, computes a cross product c = vector([0, 0, 0])
def test_addsub(self): self.assertEqual(b+a, vector([5, 8, 7])) self.assertEqual(b-a, vector([1, 0, -7]))
def test_constuctor_error(self): with self.assertRaises(TypeError): vector([[2, 3], [4, 5, 6]]) with self.assertRaises(ValueError): vector(['a','v','b'])
def test_tonumpy(self): import numpy as np self.assertEqual(vector(a.tonumpy('float64')\ - np.float64([2.0, 4.0, 7.0])), c)
from __init__ import vector import unittest a = vector([2, 4, 7]) b = vector([3, 4, 0]) c = vector([0, 0, 0]) d = vector([]) e = vector([1, 2, 3, 4, 5]) i = vector([1, 0, 0]) j = vector([0, 1, 0]) k = vector([0, 0, 1]) # Constructor errors class TestConstructor(unittest.TestCase): def test_constuctor_error(self): with self.assertRaises(TypeError): vector([[2, 3], [4, 5, 6]]) with self.assertRaises(ValueError): vector(['a','v','b']) # Sequence operations class TestSequence(unittest.TestCase): def test_len(self): self.assertEqual(len(a), 3) def test_getitem(self): self.assertEqual(a[2], 7.0) def test_getitem_error(self): with self.assertRaises(TypeError): a['i']