【问题标题】:Use fixed exponent in scientific notation在科学记数法中使用固定指数
【发布时间】:2012-01-05 22:22:28
【问题描述】:

考虑以下 Python sn-p:

for ix in [0.02, 0.2, 2, 20, 200, 2000]:
    iss = str(ix) + "e9"
    isf = float(iss)
    print(iss + "\t=> " + ("%04.03e" % isf) + " (" + str(isf) + ")")

它生成以下输出:

0.02e9  => 2.000e+07 (20000000.0)
0.2e9   => 2.000e+08 (200000000.0)
2e9     => 2.000e+09 (2000000000.0)
20e9    => 2.000e+10 (20000000000.0)
200e9   => 2.000e+11 (2e+11)
2000e9  => 2.000e+12 (2e+12)

是否有可能以某种方式“返回”?那就是:

2.000e+07 => 0.02e9 
2.000e+08 => 0.2e9
2.000e+09 => 2e9    
2.000e+10 => 20e9   
2.000e+11 => 200e9  
2.000e+12 => 2000e9

...我会指定我希望指数为e+09;然后我在这个假设函数中抛出的任何数字都返回该指数中的数值?是否可以在每种情况下为整体和小数部分指定零填充? (即000.0200e9020.0000e9)?

【问题讨论】:

    标签: python scientific-notation format-specifiers


    【解决方案1】:

    自己格式化(见Format Specification Mini-Language):

    for ix in [.02e9, .2e9, 2e9, 20e9, 200e9, 2000e9]:
        print('{:.3e} => {:0=8.3f}e9'.format(ix, ix / 1e9))
    

    输出

    2.000e+07 => 0000.020e9
    2.000e+08 => 0000.200e9
    2.000e+09 => 0002.000e9
    2.000e+10 => 0020.000e9
    2.000e+11 => 0200.000e9
    2.000e+12 => 2000.000e9
    

    说明

    {:0=8.3f} 表示“零填充,符号和数字之间的填充,总字段宽度 8,小数点后 3 位,定点格式”。

    【讨论】:

    • 非常感谢@Mark Tolonen - 我忘了自己做分区;干杯!
    【解决方案2】:

    嗯,明白了:

    for ix in [0.02, 0.2, 2, 20, 200, 2000]:
      iss=str(ix) + "e9"
      isf=float(iss)
      isf2=isf/float("1e9")
      isf2s = ("%04.03f" % isf2) + "e9"
      print(iss + "\t=> " + ("%04.03e" % isf ) + " (" + str(isf) + ")" + " -> " + isf2s )
    

    ...给出:

    0.02e9  => 2.000e+07 (20000000.0) -> 0.020e9
    0.2e9   => 2.000e+08 (200000000.0) -> 0.200e9
    2e9 => 2.000e+09 (2000000000.0) -> 2.000e9
    20e9    => 2.000e+10 (20000000000.0) -> 20.000e9
    200e9   => 2.000e+11 (2e+11) -> 200.000e9
    2000e9  => 2.000e+12 (2e+12) -> 2000.000e9
    

    抱歉发帖,
    干杯!

    【讨论】:

      【解决方案3】:

      对于那些年后仍然遇到的人......

      你可以使用 python 的 Decimal 和 quantize

      https://docs.python.org/3.6/library/decimal.html#decimal.Decimal.quantize

      【讨论】:

      • 你能说明你打算如何在这里使用它吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多