c++ - In which segment a given number lies in? -
this question has answer here:
- is floating point math broken? 20 answers
suppose have n
(integer) contiguous segments of length l
(floating point). is:
segment 0 = [0, l) segment 1 = [l, 2*l) segment 2 = [2*l, 3*l) ... segment (n-1) = [(n-1)*l, n*l)
given number x
(floating point) want determine id of segment lies inside.
my first idea following:
int segmentid = (int) floor(x/l);
anyway, not work. example, consider
double l = 1.1; double x = 5.5; int segmentid = (int) floor(x/l); //returns 5 double l = 1.1; double x = 6.6; int segmentid = (int) floor(x/l); //returns 5!!!
of course, due finite arithmetic, not work well. maybe checks required in order have robust implementation, don't know how proceed further.
the question is: how solve problem "in segment given number lies in?"
your problem neither 1.1
, nor 6.6
representable in binary floating point. when type
double l = 1.1; double x = 6.6;
you 2 numbers stored in l
, in x
, different 1.1
, 6.6
. after that, int segmentid = (int) floor(x/l);
determines correct segment different numbers, not original numbers.
you can solve problem using decimal floating point data type instead of binary. can check c++ decimal data types , exact decimal datatype c++? libraries, or implement decimal data type yourself.
but still problem remain numbers, not representable in finite decimal floating point, such 1/3
(circulating fraction), sqrt(2)
(irrational), pi
(transcendental), etc.
Comments
Post a Comment