当以科学格式显示数字时,我还没有找到一种方法只获取 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 次方,或者您是否希望它调整为最接近的 3 的lower 次方。基本上,它涉及到:您如何处理
1.50E+05
?应该是150.00E+03
还是0.15E+06
?
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
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