This is an old revision of the document!


Python Representation of RVs

I wanted to use Python to define a random variable in a pythonic way. That way, I could intuitively work with random variables from within python and potentially even use some of Python's more powerful language features in conjunction with these random variables.

x[1] right~P(X=1)

x[1, {'y':2, 'z':3}] right~P(X=1 | Y=2, Z=3)

rv.py
def rv(distFunc):
	class RV(object):
		def __init__(self, obj):
			self.obj = obj;
		def __hash__(self):
			return distFunc.__hash__();
		def __eq__(self, other):
			return self.__hash__() == other.__hash__();
		def __getitem__(self, key):
			# Case:  x[1] ==> P(X=1)
			if key.__class__ is int:
				return distFunc(self.obj, key);
			# Case:  x[1, {'y':2, 'z':3}] ==> P(X=1 | Y=2, Z=3)
			elif key[1].__class__ is dict:
				return distFunc(self.obj, key[0], key[1]);
			else:
				raise TypeError, """Invalid arguments.\n
Valid format:
    x[1] ==> P(X=1)
    x[1, {'y':2, 'z':3}] ==> P(X=1 | Y=2, Z=3)""";
 
	return property(RV);

Export page to Open Document format









You could leave a comment if you were logged in.

goplayer/rv.1297587841.txt.gz · Last modified: 2011/02/13 01:04 by aiartificer