简体   繁体   中英

Print elegantly in scientific notation python

I wanna print a number and its uncertainty in the following way:

x = (4.23 ± 0.01) e3

where the value and its uncertainty are two different variables.

mean = 4230
uncertainty = 10 
print("x is %.2e \u00B1 %.2e" % (mean, uncertainty))

I want them to be formatted with the same power of the exponential in the scientific notation. what I get is

x is 4.23e+03 ± 1.00e+01

Assuming mean integer, a way to do it might be

>>> mean = 4230
>>> uncertainty = 10 
>>> pos_to_first = len(str(mean)) - 1
>>> f"({mean/10**pos_to_first} ± {uncertainty/10**pos_to_first}) E{pos_to_first}"
'(4.23 ± 0.01) E3'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM