Significant figures calculation
Ethan Furman
ethan at stoneleaf.us
Mon Jun 27 18:58:54 EDT 2011
Harold Fellermann wrote:
> Hi Ethan,
>
>>>>>> Empirical('1200.').significance
>>> 2
>>>>>> Empirical('1200.0').significance
>>> 5
>> What about when 1200 is actually 4 significant digits? Or 3?
>
> Then you'd simply write 1.200e3 and 1.20e3, respectively.
> That's just how the rules are defined.
But your code is not following them:
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
--> from decimal import Decimal
--> 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('1.200E+3').significance
2 # should be four
--> Empirical('1.20E+3').significance
2 # should be three
--> Empirical('1.20E+4').significance
2 # should be three
The negatives appear to work, though:
--> Empirical('1.20E-4').significance
3
--> Empirical('1.2819E-3').significance
5
--> Empirical('1.2819E-1').significance
5
--> Empirical('1.281900E-1').significance
7
~Ethan~
More information about the Python-list
mailing list