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

Python: Print in scientific format with powers of ten being only multiples of 3

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

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

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

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

但是,我需要以下输出:

>>> 12.00E-03   
     1.30E-03   
    15.00E+06  
     1.60E+06  

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

好吧,这取决于您是希望输出格式始终调整为最接近的 3 的幂,还是调整为最接近的 lower 的 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)))

打印出:

1.20E-02 ->  12.00E-03
1.30E-03 ->   1.30E-03
1.50E+05 -> 150.00E+03
1.60E+06 ->   1.60E+06

情况 2:最接近 3 的幂

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_third = 3*(order_of_magnitude//3+int(order_of_magnitude%3==2))
    adjusted_mantissa = val*10**(-nearest_third)
    adjusted_mantissa_string = mantissa_template.format(adjusted_mantissa)
    adjusted_exponent_string = "+-"[nearest_third<0] + exponent_template.format(abs(nearest_third))
    return adjusted_mantissa_string+"E"+adjusted_exponent_string

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

打印出:

1.20E-02 ->  12.00E-03
1.30E-03 ->   1.30E-03
1.50E+05 ->   0.15E+06
1.60E+06 ->   1.60E+06