I've been working on some simple code for creating histograms and found that following code:
double value = 1.2;
double bucketSize = 0.4;
double bucketId = value / bucketSize;
std::cout << "bucketId as double: " << bucketId << std::endl;
std::cout << "bucketId as int: " << int(bucketId) << std::endl;
results in crazy output of:
bucketId as double: 3
bucketId as int: 2
which basically ruins my trust in computers ;) when looking for the right bucketId
for the value
while creating a histogram.
I know that there are rounding errors etc. but is there any general solution to that problem?
(Just in case) Please don't suggest adding 0.5
to result of the division before casting to int
as apparently it doesn't work very well in some cases (e.g. double value = 3; double bucketSize = 2;
)
Thanks in advance.
std::round()
will not help. – Tichonn0.5
can fail in subtle ways, see my answer here for an example near the middle. – Chasten