cdeszaq
cdeszaq

Reputation: 31280

What is the correct way to represent and manipulate probabilities and percents in 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.

Upvotes: 8

Views: 2867

Answers (2)

Gabriel
Gabriel

Reputation: 3045

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

Upvotes: 0

aioobe
aioobe

Reputation: 421020

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;

Upvotes: 5

Related Questions