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