[Tutor] specifying precision with scientific notation

Andre' Walker-Loud walksloud at gmail.com
Wed Oct 6 07:16:39 CEST 2010

```Hi Wayne,

Yes - that helps.  I missed the correct combination of parentheses.

Now I am trying to improve my aesthetics, as Evert suggested earlier

> Personally, I would print this as 7.63e-03 +- 0.83e-03, which shows the precision a bit better. But that's just a matter of aesthetics, and would make things even more complicated (then again, since you are printing numbers and formatting them, you are concerned about aesthetics).

I agree with him here, and would like to match this style.  I have been trying to figure out if you can specify the "mantissa" and exponent in scientific notation, by reading in the string.format section of python, but have been unsuccessful.  Is there an easy way to do this?  To be precise, I now have

> a = 0.0762921383941; ea = 0.000830132912068
> p = int(("%.1e" % (a / ea)).split('e')[-1])
> print(('%.' + str(int(2+p)) +'e +- %.1e') % (a, ea))
7.629e-02 +- 8.3e-04

and instead I would like this to print

7.629e-02 +- 0.083e-02

I could imagine writing a little function that does all this, but am hoping there is a quick (and dirty) way to just force the scientific notation to into this format - I guess by forcing the power of the exponent.

Thanks,

Andre

On Oct 5, 2010, at 6:39 PM, Wayne Werner wrote:

> On Tue, Oct 5, 2010 at 7:51 PM, Andre' Walker-Loud <walksloud at gmail.com> wrote:
> 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.
>
>
> a = 0.00762921383941
> ea = 0.000830132912068
>
>
> p = int(("%.1e" % (a / ea)).split('e')[-1]) # grab the power in the scientific n
> otation (is there a better way?)
> if p >= 0:
>     print(('%.' + str(int(2+p)) +'e +- %.1e') % (a, ea))
> else:
>     print('%.2e +- %.1e' % (a, ea))
>     #(desired output): 7.63e-03 +- 8.3e-04
>
>
> This works for me - I added some extra parenthesis because the original was giving me this error:
>
> Traceback (most recent call last):
>   File "exponent.py", line 7, in <module>
>     print('%.' + str(int(2+p)) +'e +- %.1e' % (a, ea))
> TypeError: not all arguments converted during string formatting
>
> HTH,
> Wayne
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101005/241bc382/attachment-0001.html>
```

More information about the Tutor mailing list