Search code examples
pythonprintingexponentialcoefficients

How to print coefficient and exponent separate from each other in python?


I would like to grab from a very large/small number (e.g., 1.324e-07) the leading coefficient by itself (1.324) and then the exponent by itself (-7) so I can send them to my .tex file as 1.324 \times 10^{-7}.

I'm writing a small script to generate tables that I will use in producing LaTeX documents. As such, my python program is generating the necessary values to fill the cells of the table. The only problem is that I would prefer to see the really small or really large numbers as C *10^n rather than Cen---e.g., 1.324x10^-7 instead of 1.324e-07. This means I need to convert my python output. Any help is much appreciated.

Here is my MWE.


mu = 1.324e-7
nu = 4.259e-5
Pr = 0.7117

f = open("my-doc.tex", "a+")
f.write("%0.3e\n" %(mu))
f.write("%0.3e\n" %(nu))
f.write("%0.4f" %(Pr))
f.close()

I would prefer something like...


mu = 1.324e-7
nu = 4.259e-5
Pr = 0.7117

f = open("my-doc.tex", "a+")
f.write("%0.3f \times 10^{%d}\n" % (coef(mu), expon(mu)))
f.write("%0.3f \times 10^{%d}\n" % (coef(nu), expon(nu)))
f.write("%0.4f" % (Pr))
f.close()

Solution

  • If you convert to string you can use split()

    def coef(n):
        return float(str(n).split("e")[0])
    
    def expon(n):
        return float(str(n).split("e")[1])