Significant figures calculation

Harold dadapapa at googlemail.com
Mon Jun 27 09:40:35 EDT 2011


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

now it's only about overriding the numerical operators :)



More information about the Python-list mailing list