计算范围内的值时出现舍入误差

Round-off error when computing value inside range

对于[0, 1]范围内的有限值v0v1和值r,如下计算的值v是否总是属于[v0, v1] 范围,还是由于四舍五入误差(略微)超出范围?

double v0;  // Finite
double v1;  // Finite
double r;   // In [0, 1]

double v = v0 * r + v1 * (1.0 - r);

if (v0 <= v1)
    assert(v0 <= v && v <= v1);
else
    assert(v1 <= v && v <= v0);

是的,可以。这是一个例子:

#include <assert.h>

int main() {

    double v0 = 2.670088631008241e-307;
    double v1 = 2.6700889402193536e-307;
    double  r = 0.9999999999232185;

    double v = v0 * r + v1 * (1.0 - r);

    if (v0 <= v1)
        assert(v0 <= v && v <= v1);
    else
        assert(v1 <= v && v <= v0);

    return 0;
}

这会产生:

Assertion failed: (v0 <= v && v <= v1), function main, file b.cpp, line 12.

本例计算出的v值为:

2.67009e-307