Matlab precision: simple subtraction is not zero

前端 未结 5 1987
野趣味
野趣味 2021-01-16 13:20

I compute this simple sum on Matlab:

2*0.04-0.5*0.4^2 = -1.387778780781446e-017

but the result is not zero. What can I do?

5条回答
  •  臣服心动
    2021-01-16 13:43

    Matlab uses double-precision floating-point numbers to store real numbers. These are numbers of the form m*2^e where m is an integer between 2^52 and 2^53 (the mantissa) and e is the exponent. Let's call a number a floating-point number if it is of this form.

    All numbers used in calculations must be floating-point numbers. Often, this can be done exactly, as with 2 and 0.5 in your expression. But for other numbers, most notably most numbers with digits after the decimal point, this is not possible, and an approximation has to be used. What happens in this case is that the number is rounded to the nearest floating-point number.

    So, whenever you write something like 0.04 in Matlab, you're really saying "Get me the floating-point number that is closest to 0.04. In your expression, there are 2 numbers that need to be approximated: 0.04 and 0.4.

    In addition, the exact result of operations like addition and multiplication on floating-point numbers may not be a floating-point number. Although it is always of the form m*2^e the mantissa may be too large. So you get an additional error from rounding the results of operations.

    At the end of the day, a simple expression like yours will be off by about 2^-52 times the size of the operands, or about 10^-17.

    In summary: the reason your expression does not evaluate to zero is two-fold:

    1. Some of the numbers you start out with are different (approximations) to the exact numbers you provided.
    2. The intermediate results may also be approximations of the exact results.

提交回复
热议问题