繁体   English   中英

使用变量将数字转换为科学计数法 python

[英]convert number to scientific notation python with a variable

我想使用str.format将 2 数字转换为提高到相同指数的科学记数法,但指数需要从str.format中扣除。 例子:

from math import log10
y=10000
x=round(np.log10(y))
m=10
y="{:e}".format(y)
m="{:e}".format(m)
print(y)
print(m)

在这里,我有 m 有 e = 1 和 ye = 4,我想要的是两者都具有相同的“e”。 我想将两者都设置为指数 x。

我认为您必须自己计算,例如使用返回字符串的帮助程序 function:

def format_exp(x, n):
    significand = x / 10 ** n
    exp_sign = '+' if n >= 0 else '-'
    return f'{significand:f}e{exp_sign}{n:02d}'

解释:

  • x是要格式化的数字, n是要显示的幂;
  • significand通过将x除以 10 n ( 10 ** n ) 来计算要显示在e前面的部分;
  • exp_sign+- ,取决于n的值(复制默认行为)。

示例用法:

>>> import math
>>> y = 10000
>>> m = 10
>>> x = math.floor(math.log10(y))  # x = 4
>>> print(format_exp(y, x))
1.000000e+04
>>> print(format_exp(m, x))
0.001000e+04
>>> print(format_exp(y, 1))
1000.000000e+01
>>> print(format_exp(m, 1))
1.000000e+01

您可以通过添加附加参数d来设置有效数字部分中打印的小数位数(默认值为6以重现默认 Python 行为)来增加此 function 的复杂性:

def format_exp(x, n, d=6):
    significand = x / 10 ** n
    exp_sign = '+' if n >= 0 else '-'
    return f'{significand:.{d}f}e{exp_sign}{n:02d}'

使用此 function,您可以控制打印的小数位数:

>>> print(format_exp(y, x))  # default behaviour still works
1.000000e+04
>>> print(format_exp(y, x, 4))
1.0000e+04
>>> print(format_exp(y, x, 1))
1.0e+04

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM