I want to calculate a Phi coefficient in Java for a Confusion Matrix 2 x 2 where the code so far as below :
double str= (trueP + falseP) *(trueP + falseN) * (trueN + falseP) * (trueN + falseN); double output= Math.sqrt(str); if (output!= 0.0) return (trueP * trueN) / output; else return 0.0; where the trueP=6930, trueN=6924, falseP=0, and falseN = 0, the output of this code is 3629.03401901938. I have calculated the Phi coefficient in excel it returns value 1 for the same values
What is the Wrong?
Any help will be highly appreciated
22 Answers
I can duplicate this error but only if trueP, trueN, falseP, and falseN are ints.
If they are ints, then this line overflows the range of int before it can be assigned to double.
double str= (trueP + falseP) *(trueP + falseN) * (trueN + falseP) * (trueN + falseN); This value is only 1.74822976E8 when it should be 2.3023989982224E15, which is larger than Integer.MAX_VALUE, a little larger than 2 billion (2E9).
Cast the first value to a double to force floating-point arithmetic for the entire expression, because double has a much larger range of valid values.
double str= ( (double) trueP + falseP) *(trueP + falseN) * (trueN + falseP) * (trueN + falseN); When I do that, I get your desired output of 1.0.
To ensure valid calculations as a whole, use doubles for all 4 variables: trueP, trueN, falseP, and falseN.
if every variable is double your code produces the desired output 1.0 :
just compile and run the following java class which assigns the values you want to be assigned to trueP, trueN, falseP and falseN:
class confusion { public static void main(String[] args) { double trueP=6930; double trueN=6924; double falseP=0; double falseN=0; double str= (trueP + falseP) *(trueP + falseN) * (trueN + falseP) * (trueN + falseN); double output= Math.sqrt(str); if (output!= 0.0) { double output2 =(trueP * trueN) / output; System.out.println(output2); } else { System.out.println(output); // Display the string. } } } the reason is that double can hold a max value big enough for your case:
static double MAX_VALUE A constant holding the largest positive finite value of type double, (2-2-52)·21023. 7