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)
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]);
				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);
class C(object):
	def y(self, _y, *_cond):
		return .4;
	def x(self, _x, *_cond):
		if len(_cond) <= 0:
			return .5;
			return .5*self.y[_cond[0][self.y]];

Export page to Open Document format

You could leave a comment if you were logged in.

goplayer/rv.txt · Last modified: 2023/02/24 23:05 (external edit)