How to Calculate Probability in Java

How to Calculate Probability in Java

By using probability, you can find the chance of occurring a specific event. It is mainly a future prediction of an event.

If you are working with a program related to Artificial Intelligence, then you may need to apply some calculations in your program to find the probability. Probability is mainly used in these cases where the outcome is uncertain for a trial.

In this article, we will see how we can calculate the probability using Java. Also, we will discuss the topic by using necessary examples and explanations to make the topic easier.

An Example of Finding the Probability in Java

In the example below, we will find the probability of a number present in an array. The code for our example is shown below:

class Probability {
  static float NPresentProbability(int a[], int ArrLength, int num) {
    float count = 0;
    for (int i = 0; i < ArrLength; i++)
      if (a[i] == num)
        count++;
    return count / ArrLength;
  }

  public static void main(String[] args) {
    int MyArray[] = {8, 7, 2, 2, 8, 7, 5};
    int FindNum = 2;
    int ArrayLen = MyArray.length;
    double PresentNum = NPresentProbability(MyArray, ArrayLen, FindNum);
    double p = (double) Math.round(PresentNum * 100) / 100;
    System.out.println("Probability of a number present in array is: " + p);
  }
}