[Tutor] class uncertainty

Christopher Smith csmith@blakeschool.org
Tue, 28 Aug 2001 02:04:44 -0500


I've created a class which keeps track of the uncertainty in a number and 
subsequent calculations performed with that number.  It works like this:

u=uncertainty #shorten the name

# define physical measurements
# with +/-1 in last digit by default
p=u('1.0')
R=u('.0821')
T=u('298')

# define a physical measurement witha larger uncertainty
n=u('1.0,.15') 

#do the calculation and look at results
v=n*R*T/p
print v
print v[0]
print v[1]

#results are 
# 24 +/- 9
# 24.4658
# 9.31980083228

I am in need of some advice now regarding two things:

1)  I want to be able to use the math functions on the class.
Should I do this as methods, e.g. x.log(), or should I redefine
the math functions so that when the module is loaded you now have

def log(x):
	if type(x)==<the type of my class>:
		return uncertain.log(x)
	return math.log(x)

I would prefer the latter so the operation is as seamless as possible.
That's where I need the advise, though.

2)  Along the same lines, I would prefer not to have to explicitly create
my class.  Is there a way to overload the "=" like the algebraic operators?
Once you load the class it would treat all numbers as strings and make them
into class instances unless, for example, they were followed by 'x' which
would denote 'exact'.  My guess this is not the way to go.

Would another approach be to write an evaluator which would work like this:

####
#put the whole 'calculation in triple quotes
res=uevaluate('''
p=1.0
R=0.0821 
T=298.15
n=1.0,.15

v=n*R*T/p
print v

in=3.0
print in*2.54x #the x denotes an exact value
'''
# and now see the results
for ri in res:
	print ri

24 +/- 9
7.6 +/- 0.3
####

Thanks for any advice.
/c