P2.3.2String formatting and physical constants
The table below gives the names, symbols, values, uncertainties and units of some physical constants.
| Name | Symbol | Value | Uncertainty | Units |
|---|---|---|---|---|
| Boltzmann constant | \(k_\mathrm{B}\) | \(1.3806504\times10^{-23}\) | \(2.4\times 10^{-29}\) | \(\mathrm{J\,K^{-1}}\) |
| Speed of light | \(c\) | \(299792458\) | (def) | \(\mathrm{m\,s^{-1}}\) |
| Planck constant | \(h\) | \(6.62606896 \times 10^{-34}\) | \(3.3\times 10^{-41}\) | \(\mathrm{J\,s}\) |
| Avogadro constant | \(N_\mathrm{A}\) | \(\;\;\,6.02214179 \times 10^{23}\) | \(3\times 10^{16}\) | \(\mathrm{mol^{-1}}\) |
| Electron magnetic moment | \(\mu_e\) | \(-9.28476377 \times 10^{-24}\) | \(2.3\times 10^{-31}\) | \(\mathrm{J/T}\) |
| Gravitational constant | \(G\) | \(\;\;\,6.67428 \times 10^{-11}\) | \(6.7 \times 10^{-15}\) | \(\mathrm{N\,m^2\,kg^{-2}}\) |
Defining variables of the form:
kB = 1.3806504e-23 # J/K
kB_unc = 2.4e-29 # uncertainty
kB_units = 'J/K'
use the string object's format method to produce the following output:
(a)
kB = 1.381e-23 J/K
(b)
G = 0.0000000000667428 Nm^2/kg^2
(c) Using the same format specifier for each line,
kB = 1.3807e-23 J/K
mu_e = -9.2848e-24 J/T
N_A = 6.0221e+23 mol-1
c = 2.9979e+08 m/s
(d) Again, using the same format specifier for each line,
=== G = +6.67E-11 [N m2 kg-2] ===
=== μe = -9.28E-24 [ J/T] ===
Hint: The Unicode codepoint for, μ, the lower case greek letter mu, is U+03BC.
(e) (Harder). Produce the output below, in which the uncertainty (one standard deviation) in the value of each constant is expressed as a number in parentheses relative the the preceding digits: that is, \(6.62606896(33) \times 10^{-34}\) means \(6.62606896 \times 10^{-34} \pm 3.3 \times 10^{-41}\).
G = 6.67428(67)e-11 Nm2/kg2
mu_e = -9.28476377(23)e-24 J/T
Show solution
(a)
print('{:s} = {:.3e} {:s}'.format(kB_symb, kB, kB_units))
(b)
print('G = {:18.16f} {:s}'.format(G, G_units))
(c)
fmt = '{:4s} = {: 11.4e} {:s}\n'*4
print(fmt.format('kB', kB, kB_units, 'mu_e', mu_e, mu_e_units, 'N_A', N_A, N_A_units,
'c', c, c_units))
(d)
print('=== {:^31s} ==='.format('G = {0:+9.2E} [{1:>9s}]'.format(G,G_units)))
print('=== {:^31s} ==='.format('\u03BCe = {0:+9.2E [{1:>9s}]'
.format(mu_e,mu_e_units)))
(e)
# The number of digits in the uncertainty to output
nsd_digits = 2
# Separate our constant into mantissa * 10^exponent
exponent = int(math.floor(math.log10(abs(G))))
mantissa = G * 10**(-exponent)
# The uncertainty digits relative to the same exponent
sd = G_unc * 10**(-exponent)
# The number of decimal places to output
dp = int(-math.log(sd,10))+nsd_digits
# The uncertainty digits as an integer
sd_digits = int(round(sd*10**dp))
print('G = {mantissa:.{dp:d}f}({sd_digits:d})e{exponent:d} {units:s}'
.format(mantissa=mantissa, dp=dp, sd_digits=sd_digits,
exponent=exponent, units=G_units))
6.67428(67)e-11
produces
G = 6.67428(67)e-11 Nm2/kg2
(and similarly for \(\mu_e\)).