paf*_*fcu 8 python formatting latex
在Python中使用格式字符串我可以轻松地以"科学记数法"打印数字,例如
>> print '%g'%1e9
1e+09
Run Code Online (Sandbox Code Playgroud)
格式化LaTeX格式数字的最简单方法是什么,即1\times10 ^ {+ 09}?
Lau*_*low 18
该siunitx乳胶包通过允许您直接使用Python浮点值,而不诉诸解析得到的字符串,使之成为有效的LaTeX的解决了这个给你.
>>> print "\\num{{{0:.2g}}}".format(1e9)
\num{1e+09}
Run Code Online (Sandbox Code Playgroud)
编译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
Run Code Online (Sandbox Code Playgroud)
测试:
>>> latex_float(1e9)
'1 \\times 10^{9}'
Run Code Online (Sandbox Code Playgroud)
安装num2tex:
pip install num2tex
Run Code Online (Sandbox Code Playgroud)
并按如下方式使用它:
>>> from num2tex import num2tex
>>> '{:.0e}'.format(num2tex(1e9))
'1 \\times 10^{9}'
Run Code Online (Sandbox Code Playgroud)
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})'
Run Code Online (Sandbox Code Playgroud)
截至目前,这在 GitHub 中尚未记录,我会尽快尝试更改!
免责声明:在使用(并赞成)Lauritz V. Thaulow 的答案一段时间(针对 Jupyter、Matplotlib 等)之后,我认为编写一个简单的 Python 模块对我的工作流程会更好,因此我在GitHub上创建了 num2tex并将其注册到皮伊。我很想获得一些关于如何使其更有用的反馈。
你可以写一个frexp10函数:
def frexp10(x):
exp = int(math.floor(math.log10(abs(x))))
return x / 10**exp, exp
Run Code Online (Sandbox Code Playgroud)
然后以LaTeX样式格式化:
'{0}^{{{1:+03}}}'.format(*frexp10(-1.234e9))
Run Code Online (Sandbox Code Playgroud)