# [Tutor] specifying precision with scientific notation

Andre' Walker-Loud walksloud at gmail.com
Wed Oct 6 02:51:49 CEST 2010

```Hi Alan,

The point I can not get to work is

> fmt = "%.%de + %.1e" % n  else:

when I try this, I get (python 2.6.5, OS X 10.6)

> n = 3; fmt = "%.%de + %.1e" % n; fmt
'%de + 3.0e+00'

But something like the "%.%de " %n is exactly what I am looking for - if I could get it to work.

Thanks,

Andre

On Oct 5, 2010, at 3:43 PM, Alan Gauld wrote:

> "Andre' Walker-Loud" <walksloud at gmail.com> wrote
>
>>> a = 0.00762921383941
>>> ea = 0.000830132912068
>>> a / ea
>> 9.190352205653852
>>
>> By default, I will print the uncertainty ("ea") with two significant digits.
>> In this example, the central value is about 10 times larger than the
>> uncertainty, so I want to print it with 3 significant figures.
>
> I don't understand why the difference but if the deciding factor is related
> to the ratio why bother with all the string stuff? Just use the ratio directly...
>
>>> p = int(("%.1e" % (a / ea)).split('e')[-1]) # grab the power in the scientific notation (is there a better way?)
>>> if p >= 0:
>
> Why not just
>
> limit = 10
> n = 3 if a/ea <= limit else n = 2 # or whatever expression is needed to calculate n
> fmt = "%.%de + %.1e" % n  else:
>
> print fmt % (a, ea)
>
>
> But I suspect I'm missing something in your reasoning about what size of n you want.
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

```