简体   繁体   English

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

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

I want to use str.format to convert 2 number to scientific notation raised to the same exponential but the exponential need to be set off the str.format .我想使用str.format将 2 数字转换为提高到相同指数的科学记数法,但指数需要从str.format中扣除。 Example:例子:

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)

here I have that m has e = 1 and ye = 4 and what I want is for both to have the same "e".在这里,我有 m 有 e = 1 和 ye = 4,我想要的是两者都具有相同的“e”。 i want to set both to exponencial x.我想将两者都设置为指数 x。

I think you have to calculate this yourself, for example using a helper function which returns a string:我认为您必须自己计算,例如使用返回字符串的帮助程序 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}'

Explanation:解释:

  • x is the number to format, and n is the power that you want to display; x是要格式化的数字, n是要显示的幂;
  • significand calculates the part to show in front of the e by dividing x by 10 n ( 10 ** n ); significand通过将x除以 10 n ( 10 ** n ) 来计算要显示在e前面的部分;
  • exp_sign is either + or - , depending on the value of n (to replicate the default behaviour). exp_sign+- ,取决于n的值(复制默认行为)。

Example usage:示例用法:

>>> 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

You can increase the complexity of this function by adding an additional parameter d to set the number of decimals printed in the significand part (with a default value of 6 to reproduce the default Python behaviour):您可以通过添加附加参数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}'

With this function, you can control the number of decimals printed:使用此 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