I need to compare extremely small numbers for an artificial intelligence project. Here is my method:
private static int maximum(BigDecimal a1, BigDecimal a2){
System.out.println(a1);
System.out.println(a2);
if (a1.compareTo(a2)<0){
return 1;
}else{
return 0;
}
Here is my output with the return value printed 3rd:
0E-917
0E-912
0
0E-918
0E-921
0
0E-932
0E-933
0
Is there any way to compare numbers this small or some simple mistake I'm making with the compareTo method? Thanks for the help!
0Ewhatever
is still 0. They're all zero.
The reason that E-932
even survives at all is because BigDecimal doesn't store just the number, it also knows what precision you're at; 0E-917
is 0, but at a certain precision.
As the spec states, compareTo
checks the actual value and disregards the precision level, thus, all of these values are 100% equal to each other: They are all 0.
EDIT: To be clear, 0E-917
is not "an extremely small number". It is zero. That precision thing is effectively: Some calculation was 0.00000000....000000
, with 917 zeroes. It might be non-zero, but if it is, it has a non-zero digit only after at least 917 zeroes, and I didn't calculate that far. This, your BD instance has absolutely no way to know that (it just stored 918 zeroes).