[英]How To Convert Number format from Scientific Notation to Number 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.