python - 为什么 %e 在格式字符串中的行为与 %g 不同?

标签 python c format-specifiers

我已经在 Python2、Python3 和 C 中尝试过这个:

为什么这些格式字符串返回的数字精度不同?

>>> "%.3e" % 123456789
'1.235e+08' 
>>> "%.3g" % 123456789
'1.23e+08' 

最佳答案

来自Python 3.7 documentation :

'e':

Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent. The default precision is 6.

'g':

General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.

The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.

Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.

A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6.

具有替代值:

>>> "%.3e" % 123
'1.230e+02'
>>> "%.3g" % 123
'123'
>>> "%.3e" % 1234
'1.234e+03'
>>> "%.3g" % 1234
'1.23e+03'

区别显然在于如何指定精度。 g似乎使用精度作为精度的正常定义,而 e使用小数点后 的位数。

关于python - 为什么 %e 在格式字符串中的行为与 %g 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30580481/

相关文章:

python - 从一个 python 文件中读取一个数组并使用 Matplotlib 绘制它

php - 使用子进程从 Python 调用 PHP

c - 使用 GCC 结构位打包的字节顺序

c - 谁提供了C头文件?

c - c中的奇怪代码

python - 乘法运算符实际上对 numpy 数组做了什么?

php - 错误的 json 数组 Python post 请求到 PHP

c++ - 如何从 swf 或 abc 文件生成 swc

c - 我已经编写了一个代码来将摄氏度转换为华氏度,但是输出太大了

c - 格式说明符 int * 警告消息