Given the following basic code:
double x = 3;
return x *-1;
I expected the return to give -3 as the result. However, the actual value I get is about 1.844674e+19 (limited by output) or a crazy large number. Doing simply return -x;
also does not work.
Changing the code as such:
double x = 3;
return x *-1.0;
Returns the correct output. This seems to be some integer vs double or Boolean issue. I understand that dividing integers without explicitly making it a double can give 0 instead of a fraction, but I have never seen it cause issues with multiplication or addition.
Can somebody tell me what happened or point to explanation of the behavior and how to deal with it?
Edit: Here is a verifiable example on my machine.
Function:
// [[Rcpp::export]]
double test1(double data)
{
std::vector<double> testArray(data);
return (testArray.size()*-1);
}
from R run with:
test1(4)
Result:
[1] 1.844674e+19
I was able to narrow down the issue to the size of of a vector. so for any positive integer size the .size() function multiplied by -1 results in the crazy value. Multiplying by -1.0 works perfectly fine.
Edit 2: I think I got it. Toby is right and it is an unsigned value that is not converted to double. In my original sample:
// [[Rcpp::export]]
double test1(double data)
{
std::vector<double> testArray(data);
double arraySize = testArray.size();
return (arraySize*-1);
}
Works perfectly fine by first converting it to a double and multiplying by -1.0 does as well.