[Tutor] class uncertainty
Roeland Rengelink
r.b.rigilink@chello.nl
Tue, 28 Aug 2001 09:56:00 +0200
Christopher Smith wrote:
>
> 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:
>
Neat
> 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:
>
I may be making an ass of myself, but according to my quick calculations
this should be closer to:
24 +/- 4
24.4658
4.4115
> 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.
>
I think this is a good solution.
> 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.
>
You cant't overload =. In Python asignment is a statement not an
operator.
Also, in the following:
radius = uncertainty(3.0, 0.2)
circumference = 2*3.1415*radius
you dont't want 2 and 3.1415 be treated as uncertain numbers. So, it is
in fact good that you have to explicit about making a numeric literal an
uncertain number. But you already noticed that. So, why are you opposed
to writing u(1) for an uncertain number but willing to write 1x for an
exact number?
> 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
> ####
>
Yep. This could be an approach. Basically, if you want to write your own
language, you have to write your own parser/evaluator. This may turn out
to be much harder than you think though. Why do that if you already have
a beautiful language (Python), that is perfectly willing to deal with
uncertain numbers, as long as you properly instantiate them?
Hope this helps,
Roeland
--
r.b.rigilink@chello.nl
"Half of what I say is nonsense. Unfortunately I don't know which half"