[Tutor] Meaning of %g ?

Alan Gauld alan.gauld at freenet.co.uk
Fri Apr 14 09:37:20 CEST 2006


>> > %g: Same as "e" if exponent is greater than -4 or less than
>> > precision, "f" otherwise.
>>
>> Yeah, thats not very clear.
>
>So what is the exact meaning ? I am still not clear.

The exact meaning is that it will use the shorter of %e and %f.
It's as simple as that., In some cases Scientific notation will be 
shorter than floating point notation. In other cases it will be 
the other way round. %g will always display the shorter one.

> Why "%.15g", "%.16g", "%.17g", "%.f", "%.16f" are different ?
>
> Why? Because Kernighan & Ritchie made them different in C.
>
> So what is the exact rules of %.g? 

As above, the shorter of %e and %f

>>> bignum = 1234567898.2345678945
>>> print "%g\n%e\n%f" % (bignum,bignum,bignum)
1.23457e+009
1.234568e+009
1234567898.234568

Hmm, that's interesting, %g is actually slightly shorter than the shortest!
One less digit. interesting...

>>> smallnum = 1234.456789
>>> print "%g\n%e\n%f" % (smallnum,smallnum,smallnum)
1234.46
1.234457e+003
1234.456789
>>> 

Hopefully you can see that in the bignum case %g used the same 
style as %e because it's shorter. In the smallnum case it used the 
same style as %f because that was shorter.

In both cases it truncated to 6 digits, which I didn't expect!!

> In doing scientific calculations, what format do I trust?

You can trust all of them, they are all correct.
None of them change the underlying value they simply display 
them differently. In practice you rarely use any of them on their 
own, you will normally add length and precision modifiers as in:

>>> print "%14.3g\n%14.3e\n%14.3f" % (bignum,bignum,bignum)
     1.23e+009
    1.235e+009
1234567898.235

Hopefully those examples show whats happening.
I have no idea why %g is dropping a digit, it may even be a bug!

Alan G.


More information about the Tutor mailing list