【问题标题】:Python: scientific notation with superscript exponentPython:带有上标指数的科学记数法
【发布时间】: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:d}e}".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://stackoverflow.com/a/29261252/8542513修改。

我尝试将https://stackoverflow.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:d}e}".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'

【问题讨论】:

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

标签: python superscript


【解决方案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:d}e}".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 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多