How to detect a double's significant digits
AnswerGuy
jimd at starshine.org
Sun May 22 22:50:00 EDT 2005
James Stroud wrote:
> Significant digits are an accounting concept. As such, it is up to
the
> accountant to keep track of these as only she knows the precision of
her
> measurements.
>
> Koan for the day:
> What are the significant digits of 0.1?
> Hint:
> >>> `0.1`
> James
> On Thursday 05 May 2005 10:37 am, so sayeth mrstephengross:
>> Hi all... How can I find out the number of significant digits (to
the
>> right of the decimal place, that is) in a double? At least, I
*think*
>> that's what I'm asking for. For instance:
>> 0.103 --> 3
>> 0.0103 --> 4
>> 0.00103 --> 5
>> 0.000103 --> 6
>> 0.0000103 --> 7
Since "significant digits" is a representation concept rather
than a mathematical one I'd be inclined to convert the value
to a string, split on the decimal point and return the length
of that.
A naive approach:
def sigdigits(x):
return len( ("%s" % float(x)).split('.')[1])
... but this gives bogus results for integers (saying that they
have "one" significant digit when, by your definition they have
zero.
I suppose you have to amend your definition to handle numbers
larger than 1 and I have to do something different than just
coercing into a float().
def sigdigits(x):
assert float(x) == x # raise an exception if we can't float it
ret = 0
strep = float(x)
(whole, fraction) = strep.split('.')
if int(fraction) > 0:
ret += len(fraction)
if int(whole) > 0:
ret += len(whole)
... I think that should do it. We could explicitly trim leading zeros
from the whole number part and trailing zeros from the fractional
part.
However I think the string representation (in Python's built-ins)
guarantees us that there will be no leading or trailing zeros unless
the part we're looking at is numerically equivalent to zero.
JimD
More information about the Python-list
mailing list