What is the correct way to represent and manage probabilities and percentages in Java?

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

Native double and float do not seem to be particularly ideal candidates, since they have problems with odd rounding, which can lead to errors when rounding occurs several times and is aggravated.

BigInteger works well for calculating permutations and combinations, and BigDecimal seems like it might be a good candidate for non-integer values, but is there something more suitable for handling percentages?

Note. In this case, the calculated probabilities are similar in nature to those associated with decks of cards, but with hundreds of cards. For more mathematics, I specifically work with Multidimensional hypergeometric_distributions .

+6
source share
2 answers

When it comes to probabilities, I suspect it will be useful for you to work with factions.

Take a look at this question:

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

+5
source

This is what I would do with a double, I think using a double would be best to get a good value with percentages ...

 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); 
0
source

Source: https://habr.com/ru/post/899815/


All Articles