以科学格式打印,十的幂只是 3 的倍数

A.W*_*enn 7 python printing string.format scientific-notation

当以科学格式显示数字时,我还没有找到一种方法只获取 3 的倍数的指数。我也没有成功编写一个简单的自定义格式化函数。

这是一个简单的例子:
使用 python 的科学记数法的正常行为.format()

numbers = [1.2e-2, 1.3e-3, 1.5e5, 1.6e6]

for n in numbers:
    print("{:.E}".format(n))
Run Code Online (Sandbox Code Playgroud)
>>> 1.20E-02  
    1.30E-03  
    1.50E+05  
    1.60E+06  
Run Code Online (Sandbox Code Playgroud)

但是,我需要以下输出:

>>> 12.00E-03   
     1.30E-03   
    15.00E+06  
     1.60E+06  
Run Code Online (Sandbox Code Playgroud)

有谁知道我获得所需格式的便捷方法?

小智 5

好吧,这取决于您是否希望输出格式始终调整为最接近的 3 次方,或者您是否希望它调整为最接近3 次方。基本上,它涉及:您如何处理1.50E+05?应该是150.00E+03还是0.15E+06

情况 1:最接近的 3 的较低幂

from math import log10,floor

numbers = [1.2e-2, 1.3e-3, 1.5e5, 1.6e6]
    
    
def adjusted_scientific_notation(val,num_decimals=2,exponent_pad=2):
    exponent_template = "{:0>%d}" % exponent_pad
    mantissa_template = "{:.%df}" % num_decimals
    
    order_of_magnitude = floor(log10(abs(val)))
    nearest_lower_third = 3*(order_of_magnitude//3)
    adjusted_mantissa = val*10**(-nearest_lower_third)
    adjusted_mantissa_string = mantissa_template.format(adjusted_mantissa)
    adjusted_exponent_string = "+-"[nearest_lower_third<0] + exponent_template.format(abs(nearest_lower_third))
    return adjusted_mantissa_string+"E"+adjusted_exponent_string

for n in numbers:
    print("{0:.2E} -> {1: >10}".format(n,adjusted_scientific_notation(n)))
Run Code Online (Sandbox Code Playgroud)

打印出:

1.20E-02 ->  12.00E-03
1.30E-03 ->   1.30E-03
1.50E+05 -> 150.00E+03
1.60E+06 ->   1.60E+06
Run Code Online (Sandbox Code Playgroud)

情况 2:最接近的 3 次幂

1.20E-02 ->  12.00E-03
1.30E-03 ->   1.30E-03
1.50E+05 -> 150.00E+03
1.60E+06 ->   1.60E+06
Run Code Online (Sandbox Code Playgroud)

打印出:

1.20E-02 ->  12.00E-03
1.30E-03 ->   1.30E-03
1.50E+05 ->   0.15E+06
1.60E+06 ->   1.60E+06
Run Code Online (Sandbox Code Playgroud)