8

When calculating and manipulating probabilities in Java, and then expressing them as percentages, what is the best data structure to use to represent them?

The native double and float don't seem like particularly ideal candidates, since they have odd rounding issues which can introduce errors when the rounding happens multiple times and gets compounded.

BigInteger works well for calculating permutations and combinations, and BigDecimal seems like it might be a good candidate for the non-integer values, but is there something more suited to dealing with percentages already?

Note: In this case, the probabilities being calculated are similar in nature to those involving decks of cards, but with hundreds of cards. For the more math-inclined, I'm specifically working with Multivariate Hypergeometric_distributions.

cdeszaq
  • 30,869
  • 25
  • 117
  • 173
  • Are they always going to be integer percentages? If so, use an int. BigInteger is overkill because your number isn't going to be any bigger than what can fit in a normal integer. – Paul Tomblin Oct 21 '11 at 19:18
  • No, the percentages will usually be in the range of [0,1], but will be displayed int a format like `23.29945%`. `BigInteger` is used for factorial calculations. – cdeszaq Oct 21 '11 at 19:25

2 Answers2

5

When it comes to probabilities, I would suspect you would benefit from working with fractions.

Have a look at this question:

Otherwise I think BigDecimal is your best choice. Beware however of the java.lang.ArithmeticException: Non-terminating decimal expansion;

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
0

This is what I would do with a double, I think that using a double would be the best for getting a good value with percent...

import java.text.NumberFormat;
//instance variable:
private static NumberFormat percent = NumberFormat.getPercentInstance();

//inside any method or event:
myAprValue = userInput / 100; 
percent = new DecimalFormat("0.0#%"); 

String st = percent.format(myAprValue); 
cdeszaq
  • 30,869
  • 25
  • 117
  • 173
Gabriel
  • 3,039
  • 6
  • 34
  • 44