【问题标题】:Print elegantly in scientific notation python以科学计数法 python 优雅地打印
【发布时间】:2020-02-16 08:54:21
【问题描述】:

我想通过以下方式打印一个数字及其不确定性:

x = (4.23 ± 0.01) e3

其中值及其不确定性是两个不同的变量。

mean = 4230
uncertainty = 10 
print("x is %.2e \u00B1 %.2e" % (mean, uncertainty))

我希望它们的格式与科学记数法中的指数幂相同。我得到的是

x is 4.23e+03 ± 1.00e+01

【问题讨论】:

  • 您需要为此编写自己的自定义逻辑,从代码开始以发现适当的比例(在您的示例中为 e3,但如果不确定性为 1e6 怎么办?)。请尝试编写代码,如果遇到困难请告诉我们。
  • 如果您只是在寻找更好的科学记数法格式,您可以考虑在输出值时使用此库。 github.com/David-OConnor/scinot

标签: python number-formatting scientific-notation


【解决方案1】:

假设平均整数,一种方法可能是

>>> mean = 4230
>>> uncertainty = 10 
>>> pos_to_first = len(str(mean)) - 1
>>> f"({mean/10**pos_to_first} ± {uncertainty/10**pos_to_first}) E{pos_to_first}"
'(4.23 ± 0.01) E3'

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 1970-01-01
    • 2014-05-26
    • 2018-11-19
    • 2012-12-14
    • 2010-10-14
    • 1970-01-01
    相关资源
    最近更新 更多