Significant figures calculation

Ethan Furman ethan at stoneleaf.us
Mon Jun 27 16:53:17 EDT 2011


Harold wrote:
> On Jun 25, 9:04 pm, Chris Torek <nos... at torek.net> wrote:
>>> I'm curious.  Is there a way to get the number of significant digits
>>> for a particular Decimal instance?
>> Yes:
>>
>> def sigdig(x):
>>     "return the number of significant digits in x"
>>     return len(x.as_tuple()[1])
> 
> Great, Chris, this is (almost) exactly what I needed.
> To make it work for numbers like 1200, that have four digits but only
> two of them being significant, I changed your snippet to the
> following:
> 
> class Empirical(Decimal) :
>     @property
>     def significance(self) :
>         t = self.as_tuple()
>         if t[2] < 0 :
>             return len(t[1])
>         else :
>             return len(''.join(map(str,t[1])).rstrip('0'))
> 
> 
>>>> Empirical('1200.').significance
> 2
>>>> Empirical('1200.0').significance
> 5

What about when 1200 is actually 4 significant digits? Or 3?

~Ethan~



More information about the Python-list mailing list