[在Python中使用LaTeX表示法格式化数字

问题描述 投票:8回答:3

在Python中使用格式字符串,我可以轻松地以“科学计数法”打印数字,例如。

>> print '%g'%1e9
1e+09

以LaTeX格式格式化数字的最简单方法是什么,即1 \ times10 ^ {+ 09}?

python formatting latex
3个回答
18
投票

siunitx LaTeX包通过允许您直接使用python float值来解决此问题,而无需诉诸解析结果字符串并将其转换为有效的LaTeX。

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

编译LaTeX文档时,以上代码将变成“在此处输入图像描述”。正如andybuckley在评论中指出的,siunitx可能不接受加号(我尚未测试过),因此可能需要对结果进行.repace("+", "")

如果不使用siunitx,请编写这样的自定义函数:

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

测试:

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

5
投票

您可以编写frexp10函数:

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

然后以LaTeX样式进行格式化:

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

1
投票

安装num2tex

pip install num2tex

并按原样使用:

>>> from num2tex import num2tex
>>> '{:.0e}'.format(num2tex(1e9))
'1 \\times 10^{9}'

[num2tex继承自str,因此可以以相同的方式使用format功能。

您还可以通过使用num2tex.configure()来更改指数的格式(添加此内容以响应@Matt的评论)。

>>>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})'

截至目前,它尚未在GitHub中记录,我将尽力对此进行更改!

免责声明:在一段时间内(针对Jupyter,Matplotlib等使用Lauritz V. Thaulow's answer),我认为最好为我的工作流程编写一个简单的Python模块,因此我在GitHub上创建了num2tex并注册它在PyPI上。我希望获得一些有关如何使其更有用的反馈。

© www.soinside.com 2019 - 2024. All rights reserved.