Python:带有上标指数的科学记数法

Posted

技术标签:

【中文标题】Python:带有上标指数的科学记数法【英文标题】:Python: scientific notation with superscript exponent 【发布时间】:2018-11-30 07:52:54 【问题描述】:

我正在尝试使用以 10 为底的指数以科学记数法格式化数字,例如使用 python 3 将 0.00123 写为 1.23x10–3

我发现了这个打印 1.23x10^-3 的很棒的函数,但是如何将插入符号指数替换为上标呢?

def sci_notation(number, sig_fig=2):
    ret_string = "0:.1:de".format(number, sig_fig)
    a,b = ret_string.split("e")
    b = int(b)         # removed leading "+" and strips leading zeros too.
    return a + "x10^" + str(b)

print(sci_notation(0.001234, sig_fig=2))      # Outputs 1.23x10^-3

函数由https://***.com/a/29261252/8542513修改。

我尝试将https://***.com/a/8651690/8542513 的答案合并到上标格式,但我不确定 sympy 如何处理变量:

from sympy import pretty_print as pp, latex
from sympy.abc import a, b, n

def sci_notation(number, sig_fig=2):
  ret_string = "0:.1:de".format(number, sig_fig)
  a,b = ret_string.split("e")
  b = int(b)             #removed leading "+" and strips leading zeros too.
  b = str(b)
  expr = a + "x10"**b    #Here's my problem
  pp(expr)               # default
  pp(expr, use_unicode=True)
  return latex(expr)

print(latex(sci_notation(0.001234, sig_fig=2))) 

返回:TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

【问题讨论】:

您在哪里打印?并非所有内容都支持上标(例如,控制台) 我想将该函数应用于熊猫数据框。 ***.com/a/8651690/8542513 的代码在 Jupyter Notebook 中打印指数。 它只是在不同的行中打印n,使它看起来像一个(格式错误的)指数 你想要的结果是什么?你想要数字为 0.001234 还是 1.23x10^-3 。 我希望以 10 为底的指数作为上标(见问题的第一行) 【参考方案1】:

这是一个简单的解决方案:

def SuperScriptinate(number):
  return number.replace('0','⁰').replace('1','¹').replace('2','²').replace('3','³').replace('4','⁴').replace('5','⁵').replace('6','⁶').replace('7','⁷').replace('8','⁸').replace('9','⁹').replace('-','⁻')

def sci_notation(number, sig_fig=2):
    ret_string = "0:.1:de".format(number, sig_fig)
    a,b = ret_string.split("e")
    b = int(b)         # removed leading "+" and strips leading zeros too.
    return a + "x10^" + SuperScriptinate(str(b))

【讨论】:

你的-1 看起来像_1。你还忘记了第一个函数定义上的:。有宝宝-吗? 我已经解决了您发现的问题,@Ev.Kounis,谢谢。有一个宝贝-。这里是【参考方案2】:

我认为你的主要问题是how can the caret-exponent be replaced with a superscript?

如果你在 Jupyter notebook 中使用 python,有一个简单的方法:

  from IPython.display import display, Math, Latex

  # if the number is in scientific format already
  display(Math('2.14e-6'.replace('e', r'\times 10^') + ''))

  # if it is not:
  d = "%e" % (number)
  # then use the above form: display(Math(d.replace('e', r'\times ...

【讨论】:

以上是关于Python:带有上标指数的科学记数法的主要内容,如果未能解决你的问题,请参考以下文章

Python中科学计数法中的指数数字

强制python不以标准形式/科学记数法/指数形式输出浮点数[重复]

从科学记数法中提取指数

在pandas python中将指数或科学数转换为整数

尝试用 Java 编写科学计算器但无法使指数按钮工作

如何在 Python 中将负指数数转换为十进制数?