In: Computer Science
Run the following code and explain the results (expectation of the array). Test it on the following arrays: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] [1.0, 4.0, 6.0,2.0 , 3.0, 5.0] [5.0, 3.0, 2.0, 6.0, 4.0, 1.0] [6.0, 5.0, 4.0, 3.0, 2.0, 1.0] // Java code to calculate expected // value of an array import java.io.*; class GFG { // Function to calculate expectation static float calc_Expectation(float a[], float n) { // Variable prb is for probability of each // element which is same for each element float prb = (1 / n); // calculating expectation overall float sum = 0; for (int i = 0; i < n; i++) sum += a[i] * prb; // returning expectation as sum return sum; } // Driver program public static void main(String args[]) { float expect, n = 6f; float a[] = { 1f, 2f, 3f, 4f, 5f, 6f }; // Function for calculating expectation expect = calc_Expectation(a, n); // Display expectation of given array System.out.println("Expectation of array E(X) is : " + expect); } }
Given program:
import java.io.*;
public class GFG {
// Function to calculate expectation
static float calc_Expectation(float a[], float n) {
// Variable prb is for probability of each
// element which is same for each element
float prb = (1 / n);
// calculating expectation overall
float sum = 0;
for (int i = 0; i < n; i++)
sum += a[i] * prb;
// returning expectation as sum
return sum;
} // Driver program
public static void main(String args[]) {
float expect, n = 6.0f;
float a[] = {1f, 2f, 3f, 4f, 5f, 6f};
// Function for calculating expectation
expect = calc_Expectation(a, n);
// Display expectation of given array
System.out.println("Expectation of array E(X) is : " +
expect);
}
}
Explanation:
the array is taken input to calc_Expectation() function
probability is 1/n = 1/6 in all cases given
multiply all elements if array with prb and add them to variable sum
for all the given arrays the output will be same because elements inside the array are same.
Output:
for array: a = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
Output:
for array: a = [1.0, 4.0, 6.0,2.0 , 3.0, 5.0]
Output:
for array: a = [5.0, 3.0, 2.0, 6.0, 4.0, 1.0]
Output:
for array: a = [6.0, 5.0, 4.0, 3.0, 2.0, 1.0]