C/C++: 1.00000 <= 1.0f = False

后端 未结 3 809
盖世英雄少女心
盖世英雄少女心 2021-01-18 07:49

Can someone explain why 1.000000 <= 1.0f is false?

The code:

#include 
#include 

using namespace std;

int main(in         


        
3条回答
  •  悲&欢浪女
    2021-01-18 08:17

    As correctly pointed out in the comments, the value of t is not actually the same 1.00000 that you are defining in the line below.

    Printing t with higher precision with std::setprecision(20) will reveal its actual value: 1.0000001192092895508.

    The common way to avoid these kinds of issues is to compare not with 1, but with 1 + epsilon, where epsilon is a very small number, that is maybe one or two magnitudes greater than your floating point precision.

    So you would write your for loop condition as

    for(t = 0; t <= 1.000001f; t += step)
    

    Note that in your case, epsilon should be atleast ten times greater than the maximum possible floating point error, as the float is added ten times.

    As pointed out by Muepe and Alain, the reason for t != 1.0f is that 1/10 can not be precisely represented in binary floating point numbers.

提交回复
热议问题