I am reimplementing some Java code in C++ using JNI for speed improvements. To test my new code, I am comparing the outputs of the Java code with the C code. I have noticed that the C and Java codes are producing slightly different solutions when performing double calculations.
The problem comes when applying the sigmoid function, f(x) = 1 / (1 + e ^ -x), to a matrix. If I input a matrix containing 0.9595328833775463, Java produces 0.7230282708475686 and C produces 0.7230282708475684. I originally assumed it was just rounding when printing, but the binary doesn't match either.
I'm using Java 16.0.1 and Apple clang 12.0.5.
Specifically, this is the offending code:
Note: a and output are both 2d double arrays of dimensions height x width.
Java Version:
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
output[i][j] = (1.0 / (1 + Math.exp(-a[i][j])));
}
}
C++ version:
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
output[i][j] = (1.0 / (1 + exp(-1 * a[i][j])));
}
}
Edited question:
I'm aware there should be some error in the calculation, but I would like both of these calculations to have the same error. I have already validated my Java implementation and don't want to need to revalidate my code with the new errors. This is being used in neural net training and I'm not sure how the compounding errors will affect the outcome after a few million calculations. Is there a way I can calculate this in C in such a way that the outcomes match?