Format number using LaTeX notation in Python

◇◆丶佛笑我妖孽 提交于 2019-12-09 05:36:57

问题


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}?


回答1:


The siunitx LaTeX package solves this for you by allowing you to use the python float value directly without resorting to parsing the resulting string and turning it into valid LaTeX.

>>> print "\\num{{{0:.2g}}}".format(1e9)
\num{1e+09}

When the LaTeX document is compiled, the above code will be turned into

. As andybuckley points out in the comments, the plus sign might not be accepted by siunitx (I've not tested it), so it may be necessary to do a .repace("+", "") on the result.

If using siunitx is somehow off the table, write a custom function like this:

def latex_float(f):
    float_str = "{0:.2g}".format(f)
    if "e" in float_str:
        base, exponent = float_str.split("e")
        return r"{0} \times 10^{{{1}}}".format(base, int(exponent))
    else:
        return float_str

Testing:

>>> latex_float(1e9)
'1 \\times 10^{9}'



回答2:


You can write a frexp10 function:

def frexp10(x):
    exp = int(math.floor(math.log10(abs(x))))
    return x / 10**exp, exp

Formatting in LaTeX style is then:

'{0}^{{{1:+03}}}'.format(*frexp10(-1.234e9))



回答3:


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.



来源:https://stackoverflow.com/questions/13490292/format-number-using-latex-notation-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!