floating point number imprecision while iterating

后端 未结 3 843
天涯浪人
天涯浪人 2021-01-06 21:30

I have a function that computes a point in 3d spaced based on a value in range [0, 1]. The problem I\'m facing is, that a binary floating-point number canno

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 22:06

    for (t=0; t <= 1.0; t += 0.1) {
    

    your problem is that a binary floating point number cannot exactly represent 0.1.

    The closest 32-bit single precision IEEE754 floating point number is 0.100000001490116119384765625 and the closest 64-bit double precision one 0.1000000000000000055511151231257827021181583404541015625. If the arithmetic is performed strictly at 32-bit precision, the result of adding 0.1f ten times to 0 is

    1.00000011920928955078125
    

    If intermediate computations are performed at greater precision than float has, it could result in exactly 1.0 or even slightly smaller numbers.

    To fix your problem, in this case you could use

    for(k = 0; k <= 10; ++k) {
        t = k*0.1;
    

    because 10 * 0.1f is exactly 1.0.

    Another option is to use a small tolerance in your curves_bezier function,

    if (t > 1 && t < 1 + epsilon) {
        t = 1;
    }
    

    for a suitably small epsilon, maybe float epsilon = 1e-6;.

提交回复
热议问题