Using format strings in Python I can easily print a number in "scientific notation", e.g.
>> print '%g'%1e9
1e+09
What is the simplest way to format the number in LaTeX format, i.e. 1\times10^{+09}?
PythonTeX is a LaTeX package that allows Python code in LaTeX documents to be executed and provides access to the output. This makes possible reproducible documents that combine results with the code required to generate them. Calculations and figures may be next to the code that created them.
Python has a defined syntax for representing a scientific notation. So, let us take a number of 0.000001234 then to represent it in a scientific form we write it as 1.234 X 10^-6. For writing it in python's scientific form we write it as 1.234E-6. Here the letter E is the exponent symbol.
0 - It is the character that is placed in place of the empty spaces. 9 - It is the width option that sets the minimum width of the number to 9 (including decimal point, thousands comma and sign) . 3 - It is the precision operator that sets the precision of the given floating number to 3 places.
Install num2tex:
pip install num2tex
and use it as so:
>>> from num2tex import num2tex
>>> '{:.0e}'.format(num2tex(1e9))
'1 \\times 10^{9}'
num2tex
inherits from str
so the format
function can be used in the same way.
You can also change the format of the exponent by using num2tex.configure()
(adding this in response to @Matt's comment).
>>>from num2tex import num2tex
>>>from num2tex import configure as num2tex_configure
>>>num2tex_configure(exp_format='cdot')
>>>num2tex(1.3489e17)
'1.3489 \cdot 10^{17}'
>>>num2tex_configure(exp_format='parentheses')
'1.3489 (10^{17})'
As of now this is undocumented in the GitHub, I'll try to change this soon!
Disclaimer: After using (and upvoting) Lauritz V. Thaulow's answer for a while (for Jupyter, Matplotlib etc.) I thought it would be better for my workflow to write a simple Python module, so I created num2tex on GitHub and registered it on PyPI. I would love to get some feedback on how to make it more useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With