Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to represent and manipulate probabilities and percents in Java?

Tags:

java

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.

like image 516
cdeszaq Avatar asked Oct 21 '11 19:10

cdeszaq


People also ask

How do you represent percentages in Java?

You would use the division operator to divide the percentage by one hundred. Example: System. out. println(50/100); 50% equals 50/100, which is 0.5.


1 Answers

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

Have a look at this question:

  • Best way to represent a fraction in Java?

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

like image 155
aioobe Avatar answered Oct 04 '22 22:10

aioobe