I'm curious if anyone has been able to get correct results when dividing matrices (with double values) with a scalar (double). I noticed OpenCV does not give correct (well, "exact") results when I was trying to track down the source of some inconsistencies between an algorithm in MATLAB and one being reproduced in C++. Here is a minimal example of the problem I'm seeing:
cv::Mat some_matrix(1, 1, CV_64FC1, cv::Scalar::all(95));
cv::Mat some_matrix_div = some_matrix / 235.0;
printf(
"Expected: %.53g\n"
"OpenCV : %.53g\n",
some_matrix.at<double>(0,0) / 235.0,
some_matrix_div.at<double>(0,0) );
After running I see
Expected: 0.40425531914893614304773450385255273431539535522460938
OpenCV : 0.404255319148936198558885735110379755496978759765625
The first is what the value should be (and what you'll get if you perform the double precision division of 95/235 in C++ or MATLAB) but the second is what OpenCV produces upon using the division operator. I tried tracking down the problem in the OpenCV source code but the matrix operations are a bit convoluted and I don't have a whole lot of time at the moment to rifle through it, so I'm wondering if anyone else has encountered this problem and knows a fix?
EDIT
I'll add some clarification.
First, I know doubles are not exact numeric representations. What I meant by "exact" (why it was in quotes) was the double division performed outright (e.g. printing the result of 95.0/235.0) is not exactly the same as what OpenCV does when you divide a matrix by a scalar, despite that the value in the matrix is indeed stored as a double, and the scalar is indeed treated as a double as well. One would expect the two results should be identical; namely, if I divide a double by another double, the result should be the same as an OpenCV double matrix divided by a double scalar.
I have also already tried explicitly casting all numeric constants as doubles in the code, with no success.
While it's true in this case the difference is relatively small (e^-16), I'm not sure how this might possibly compound to make larger and larger errors over time. That's one issue. The other is more of a minor annoyance, a misunderstanding why OpenCV isn't doing what one would intuitively expect it to. In the end it may not cause any issues, but if the odd behavior can be avoided I'd obviously prefer that, especially since it makes it unclear when a calculation does not match the expected outcome from the MATLAB results because of a calculation oddity or because of an actual algorithm implementation issue (which is what I assumed it was).
Hopefully that's more clear.