# [Tutor] specifying precision with scientific notation

Evert Rol evert.rol at gmail.com
Tue Oct 5 22:15:00 CEST 2010

> I want to print scientific numbers with a specified number of decimal places.  However, I want the number printed to be dynamically determined by the data.  Example:
>
>> 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.

Note that 'specified number of decimal places' != 'number of significant digits'. But it's fairly obvious you mean significant digits here.
But that aside, perhaps Python's decimal module can help you to ease things: http://docs.python.org/library/decimal.html

>  So I want to do something like
>
>> p = int(("%.1e" % (a / ea)).split('e')[-1]) # grab the power in the scientific notation (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

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).

But if the decimal module can't make it easier for you, I don't really think there's an easy way of doing this.
Though you may want to make things slightly more convenient by creating your own Float class (inheriting from float), or even a Value class that has a number and an error. Then override the the __str__ method and you should be done for any number you print, while all the other operations can work as float (for the first class at least), or similar to float (second class).

Cheers,

Evert

> but this fails.  And I haven't figured out how to get this to work.  Seems like it should be simple.
>
> Any help?
>
>
> Thanks,
>
> Andre