打印由另一个变量设置的精度的浮点变量

leo*_*887 1 python precision rounding string-formatting

使用 python,我想打印两个变量(浮点数)的值。打印两个变量的精度应取决于变量值本身。事实上,我将打印一个值和相关的错误。我事先不知道“Value”和“Error”会有多少个相关数字。

下面是一些例子:

Value: 15236.265, Error = 0.059 --> printed value 15236.27 +- 0.06
Value: 15236.265, Error = 3.738 --> printed value 15236 +- 4
Value: 15236.265, Error = 275.658 --> printed value 15200 +- 300
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想确定打印语句中使用的精度,如下所示。

print(Value is {???} and error is {:.1g}).format(value, error)
Run Code Online (Sandbox Code Playgroud)

您有什么建议吗?我确信解决方案相当简单,但我找不到它。

Ala*_* T. 5

如果您使用格式字符串,这会容易得多,因为您甚至可以替换其中的格式参数。这将让您以编程方式控制所有属性:

value = 15236.265
error = 3.738
p1    = 10
p2    = 3
print(f"Value is {value:.{p1}g} and error is {error:.{p2}g}")

# 'Value is 15236.265 and error is 3.74'
Run Code Online (Sandbox Code Playgroud)

编辑

我从您的评论中看到,这不是格式问题,而是舍入问题。您想要对误差的尾数进行舍入并对值本身应用相同的舍入。

这是一个可以为您完成此操作的函数:

from math import log
def roundError(N,E):
    p=-round(log(E,10)-0.5)
    return round(N,p),round(E,p)

roundError(15236.265,0.059)   # --> (15236.26, 0.06)
roundError(15236.265,3.738)   # --> (15236, 4)
roundError(15236.265,275.658) # --> (15200, 300)  
Run Code Online (Sandbox Code Playgroud)

然后您可以打印这些数字,无需任何特殊格式。

这可能不是你关心的问题,但我想指出的是,这个值/误差调整将稍微抵消误差范围内可能值的范围。

例如:

15236.265 +/- 275.658 ==> 14960.607 ... 15511.923
15200     +/- 300     ==> 14900     ... 15500  (extra 60 low and missing 12 high)
Run Code Online (Sandbox Code Playgroud)

为了谨慎起见,可能需要舍入值范围为 14950 ... 15550,即 15250 +/- 300。换句话说,将值舍入到误差大小的一半,round(2*N,p)/2以考虑应用于舍入的情况值范围。