Reputation: 26333
I witness numerical differences between Matlab and C++ code. Discrepancy seems to stem from different output for sqrt method in Matlab and C++. For very small numbers (< 10-5) it seems that relative difference is quite big.
Which approach would you suggest to
EDIT
I add more precision about the code.
float* buttonVar = new float[nBut];
for (int_T ibut = 0; ibut < nBut; ibut++)
{
for (int_T id = start_idx; id <= stop_idx; id++)
{
inputArray[id - start_idx] = arr[ibut * nDepth + id];
}
reduceVector(inputArray, reducedArray, inputarray_size, d1, d2);
buttonMean[ibut] = 0;
buttonVar[ibut] = 0;
for (int_T id = 0; id < min(nd, nDepth); id++)
{
buttonMean[ibut] += reducedArray[id] / float(nd);
}
for (int_T id = 0; id < min(nd, nDepth); id++)
{
buttonVar[ibut] += (reducedArray[id] - buttonMean[ibut])
*(reducedArray[id] - buttonMean[ibut]);
}
buttonVar[ibut] = sqrtf(buttonVar[ibut] / float(nd));
}
In Matlab, I am converting to single
the number to be sqrt
. Discrepancy in the code appears in buttonVar
.
Final results that are compared in Google Tests are results from several more operations with no other call to mathematics functions. These additional operations are in methods which were thouroughly Google Tested, and there is perfect match to float precision of outputs for these tests.
Numerical difference in buttonVar
is up to 15% relative difference (=100*abs(cpp_res - matlab_res)/matlab_res. Significant relative difference occurs when buttonVar
his of order of magnitude 10e-6.
Upvotes: 0
Views: 469
Reputation: 26333
Converting to double in C++ inside the computation solves the difference problem. We reach a very satisfactory match after converting to double.
Upvotes: 0