MST

星途 面试题库

面试题:Python浮点数运算误差在复杂计算中的传播及补偿

假设有一个复杂的数学计算流程,涉及多个浮点数的加减乘除运算,在运算过程中浮点数误差不断积累。请设计一个函数,该函数接收一个包含多个浮点数运算步骤的列表(如[(0.1, '+', 0.2), (result, '*', 0.5) ,这里result是上一步运算结果],通过合理的误差补偿策略,尽量减小最终结果的误差并返回。
28.3万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
from decimal import Decimal


def calculate_with_error_compensation(operations):
    result = Decimal(str(operations[0][0]))
    for num, operator, operand in operations[1:]:
        if operator == '+':
            result += Decimal(str(operand))
        elif operator == '-':
            result -= Decimal(str(operand))
        elif operator == '*':
            result *= Decimal(str(operand))
        elif operator == '/':
            result /= Decimal(str(operand))
    return float(result)


你可以这样调用这个函数:

operations = [(0.1, '+', 0.2), (0.3, '*', 0.5)]
print(calculate_with_error_compensation(operations))

上述代码使用Python的decimal模块来处理浮点数运算,decimal模块可以提供更高的精度,减少浮点数运算的误差。函数calculate_with_error_compensation接受一个包含运算步骤的列表,列表中的每个元素是一个三元组,分别表示操作数1、操作符和操作数2 。函数使用Decimal类型进行运算,最后将结果转换回float类型返回。