/cas/vectors.py

https://bitbucket.org/twright/c1000-intelligent-calculator
Python | 88 lines | 49 code | 21 blank | 18 comment | 7 complexity | 3795c2b1154d8285e54abfd733e26fcf MD5 | raw file
  1. #!/usr/bin/env python
  2. from __future__ import division
  3. __author__ = 'Tom Wright <tom.tdw@gmail.com>'
  4. # Copyright 2012 Thomas Wright <tom.tdw@gmail.com>
  5. # This file is part of C1000 Intelligent Calculator.
  6. #
  7. # C1000 Intelligent Calculator is free software: you can redistribute it
  8. # and/or modify it under the terms of the GNU General Public License as
  9. # published by the Free Software Foundation, either version 3 of the License,
  10. # or (at your option) any later version.
  11. #
  12. # C1000 Intelligent Calculator is distributed in the hope that it will be
  13. # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
  15. # Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along with
  18. # C1000 Intelligent Calculator. If not, see <http://www.gnu.org/licenses/>.
  19. from operator import add, mul
  20. from cas.core import Algebra
  21. from cas.core import handle_type as ht
  22. class Vector(tuple, Algebra):
  23. ''' A class representing an vector or list '''
  24. def __str__(self):
  25. s = lambda a: str(+a)
  26. return '[' + ', '.join(list(map(s, self))) + ']'
  27. def __add__(self, other):
  28. return self.__class__(map(add, self, other))
  29. __radd__ = __add__
  30. def __sub__(self, other):
  31. return self + -other
  32. def __rsub__(self, other):
  33. return -self + other
  34. def __neg__(self):
  35. return self.__class__(map(lambda a: -a, self))
  36. def __mul__(self, other):
  37. if isinstance(other, self.__class__):
  38. return sum(map(mul, self, other))
  39. else:
  40. return self.__class__(map(lambda a: a * other, self))
  41. __rmul__ = __mul__
  42. def norm(self):
  43. ''' Return the Euclidian Norm of a vector '''
  44. square = lambda a: a ** 2
  45. return sum(map(square, self))**ht('0.5')
  46. def __len__(self):
  47. return ht(super(type(self), self).__len__())
  48. def mean(self):
  49. return sum(self) / len(self)
  50. def Sxx(self):
  51. return sum(self)**ht(2) - self.mean() * len(self)
  52. def variance(self):
  53. return self.Sxx() / (len(self) - ht(1))
  54. def stdev(self):
  55. return self.variance() ** ht('0.5')
  56. def product(self):
  57. return reduce(mul, self, ht(1))
  58. def median(self):
  59. xs = sorted(self)
  60. midpoint = round(len(xs)/2)
  61. return xs[midpoint] if len(xs) % 2\
  62. else ht(xs[midpoint] + xs[midpoint-1]) / ht(2)
  63. def mode(self):
  64. counts = {}
  65. for x in self:
  66. counts[x] = counts[x] + 1 if x in counts else 1
  67. return max(counts)