Reputation: 35
I was calculating a simple combination using java, when I define the result as double, the answer seems right, only lost some precision, but when I use the BigInteger class, the answer looks just wrong at all, I don't see why it's like that, here is the code.
import java.math.BigInteger;
import java.util.Scanner;
public class Test {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please input the lottery sum");
int num = in.nextInt();
System.out.println("Please input the available sum");
int avail = in.nextInt();
//double sum = 1;
BigInteger sum = BigInteger.ONE;
for (int i = avail - 1; i >= 1;i--){
//sum = sum*(num - i) / i;
sum = sum.multiply(BigInteger.valueOf(num - i)).divide(BigInteger.valueOf(i));
}
//sum = sum * num / avail;
sum = sum.multiply(BigInteger.valueOf(num)).divide(BigInteger.valueOf(avail));
System.out.println(sum);
in.close();
}
}
Upvotes: 1
Views: 346
Reputation: 139
I'm not sure what you're calculating, but I suspect that the integer division is what's causing the observed differences.
I suppose that you get the same result with BigInteger and a regular int for small examples.
For example: double: 3.0/2.0 = 1.5
(Big)Integer: 3/2 = 1
If you sum over such divisions multiple times, the discrepancy gets bigger and bigger.
Take a look at BigDecimal, that may be the solution you're after to avoid this error introduced by integer divisions.
Upvotes: 0
Reputation: 500257
The main difference between double
and BigInteger
is that one is using float-point maths, and other is using integer maths. This means that, when you using BigInteger
, the result of every division gets truncated.
Upvotes: 3