[Tutor] Rounding to n significant digits?

Gregor Lingl glingl at aon.at
Sun Jul 4 06:44:05 EDT 2004



Tim Peters schrieb:

>
>Then it's time to learn about one of the more obscure features of
>string formats:  if you put an asterisk in a string format where a
>precision specifier is expected, the actual precision to use will be
>taken from the argument tuple. 
>
O.k. I took the opportunity to do so.

> I realize that's confusing; that's why
>I called it obscure <wink>.  It should be clearer from this rewrite of
>your rewrite of my original round_to_n function:
>
>def round_to_n(x, n):
>    if n < 1:
>        raise ValueError("number of significant digits must be >= 1")
>    return "%.*e" % (n-1, x)
>
>That's probably the end of the line for this problem <wink>.
>  
>
Since long I appreciate very much the beauty and elegance of Tim's 
solutions, even to
quasi "every day problems". (Yes, I know, 20+ years of experience ... ;-) )

>A related but harder problem is to get a string rounded to n
>significant digits, but where the exponent is constrained to be a
>multiple of 3.  This is often useful in engineering work.  For
>example, in computer work, 1e6 and 1e3 are natural units (mega and
>kilo), but 1e4 isn't -- if I have 15,000 of something, I want to see
>that as 15e3, not as 1.5e4.  I don't know an easy way to get that in
>Python (or in most other programming languages).
>
>  
>
I suppose if Tim says this, there *is no* easy way.
However, the result of my tinkering around with string formats
(see remark above - and assuming that using regular
expressions is not 'easy' (at least for me) - ) is:

def eng_round_to_n(x,n):
    man,exp = round_to_n(x, n).split("e") # contains error-handling
    sh=int(exp)%3
    return "%.*fe%+04i" % (n-1-sh,float(man)*10**sh,int(exp)-sh)

1. is it correct?
2. doesn't it call for a pinch of elegance and streamlining?

Regards, Gregor



More information about the Tutor mailing list