如何将错误值从速记符号转换为标准形式

  • 本文关键字:转换 符号 标准 错误 python
  • 更新时间 :
  • 英文 :


在简短的错误表示法中,一个值及其相应的错误显示为

value(error)

其中error表示value最后几位的误差。例如

12345.67(89) == 12345.67 +/- 0.89
1234.5(6789) == 1234.5 +/- 678.9

在第二个示例中,1234.5的后4位数字有错误,由于小数点后面有一位数字,因此6789也将具有相同的形式。我目前的解决方案可以工作,但在执行时似乎效率低下,特别是在解析大型数据集时。

value = 12345.67
error =78
print(f'Result = {value}({error})')
if '.' in str(value): # Check for decimal point  
decimals = str(value).split('.')[1] #capture the numbers following the decimal place
dec_len = len(decimals) # how many digits after the decimal point 
error = error / (10**dec_len) # divide error by 10^number_of_decimals
# If no decimal point, the error is absolute 12345.6(789)=12345.6+/-789
print('This is equivalent to:')
print(f'Result = {value}+/-{error}')

将整数转换为字符串并操作它很慢。迭代地乘以一个数字直到它是整数会更快。

def convert_error(value, error):
decimals = 0
while value != int(value):
value *= 10
decimals += 1
return error / 10**decimals

根据我的时间安排,这是你的方法的一个数量级改进。