How to detect a double's significant digits

Jeremy Bowers jerf at jerf.org
Thu May 5 23:02:06 EDT 2005


On Fri, 06 May 2005 02:44:43 +0000, Grant Edwards wrote:

> On 2005-05-05, Jeremy Bowers <jerf at jerf.org> wrote:
> 
>> Since I think he mentioned something about predicting how much space it
>> will take to print out, my suggestion is to run through whatever
>> printing routines there are and get a string out,
> 
> A step which will require him to tell the printing routine how many digits
> he wants printed.

Not necessarily; consider the str() of a float in Python, especially given
the "significant digits" aspect (it may be ill-defined, but I can think of
several well-defined ways to mean that, where str() embodies one of them).
The easiest way to tell how long the number will be when str prints it out
is to simply ask it.

In C++, this may be harder, as your output software may insist on
rendering everything directly, with no way to reach in and tell what it
did. Imagine the standard IOStreams, without the ability to stream into a
string. Now it's a lot harder to tell. So if you've got something "smart"
like the default str() in Python, you may not be able to tell in advance
what it is going to do, short of trying to manually reverse engineer it.
I've tried that a few times, and in each instance, I can get 95-99%... but
I never quite make it to 100%, usually because I find a bug somewhere and
can't figure out how to characterize and replicate it.

(The biggest of these so far was when I tried to reconstruct Tk's wrapping
in a text widget, so I could tell how many screen lines the given piece of
text I produced would consume, whereupon I discovered Tk didn't correctly
wrap all Unicode characters... it correctly (as far as I could see)
reported their widths, but happily let the characters run right off the
right edge of the widget under certain circumstances I could never
characterize without putting in even more effort than I cared to. The bugs
aren't always *important*, one can imagine the opposite problem of
wrapping a little too quickly, and it could be years before anyone notices
if it's just a few pixels off in the right direction, but it'll still
screw you up if you try to replicate it.)




More information about the Python-list mailing list