Compute Expected Value of a Discrete Distribution in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to compute the expected value of a discrete distribution in C programming language. The lab covers the following steps: reading the values and probabilities, calculating the expected value by summing the product of each value and its corresponding probability, and printing the final result. The program allows users to input the number of outcomes, the values, and their respective probabilities, and then displays the input values for verification. This lab aims to provide a practical understanding of probability and combinatorics using C, which is a valuable skill in various fields, such as data analysis, machine learning, and decision-making.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435345{{"`Compute Expected Value of a Discrete Distribution in C`"}} c/for_loop -.-> lab-435345{{"`Compute Expected Value of a Discrete Distribution in C`"}} c/arrays -.-> lab-435345{{"`Compute Expected Value of a Discrete Distribution in C`"}} c/user_input -.-> lab-435345{{"`Compute Expected Value of a Discrete Distribution in C`"}} c/math_functions -.-> lab-435345{{"`Compute Expected Value of a Discrete Distribution in C`"}} end

Read Values and Probabilities

In this step, you'll learn how to read values and probabilities for computing the expected value of a discrete distribution in C. We'll create a program that allows users to input multiple values and their corresponding probabilities.

First, let's create a new C file in the ~/project directory:

cd ~/project
nano expected_value.c

Now, let's write the initial code to read values and probabilities:

#include <stdio.h>

#define MAX_OUTCOMES 10

int main() {
    double values[MAX_OUTCOMES];
    double probabilities[MAX_OUTCOMES];
    int num_outcomes;

    printf("Enter the number of outcomes (max %d): ", MAX_OUTCOMES);
    scanf("%d", &num_outcomes);

    // Input values
    printf("Enter the values:\n");
    for (int i = 0; i < num_outcomes; i++) {
        printf("Value %d: ", i + 1);
        scanf("%lf", &values[i]);
    }

    // Input probabilities
    printf("Enter the probabilities:\n");
    for (int i = 0; i < num_outcomes; i++) {
        printf("Probability %d: ", i + 1);
        scanf("%lf", &probabilities[i]);
    }

    // Print input for verification
    printf("\nInput Values:\n");
    for (int i = 0; i < num_outcomes; i++) {
        printf("Value %d: %.2f, Probability %d: %.2f\n",
               i + 1, values[i], i + 1, probabilities[i]);
    }

    return 0;
}

Compile and run the program:

gcc expected_value.c -o expected_value
./expected_value

Example output:

Enter the number of outcomes (max 10): 3
Enter the values:
Value 1: 10
Value 2: 20
Value 3: 30
Enter the probabilities:
Probability 1: 0.2
Probability 2: 0.5
Probability 3: 0.3

Input Values:
Value 1: 10.00, Probability 1: 0.20
Value 2: 20.00, Probability 2: 0.50
Value 3: 30.00, Probability 3: 0.30

Key points to understand:

  • We use arrays to store values and probabilities
  • MAX_OUTCOMES defines the maximum number of possible outcomes
  • scanf() is used to read user input for values and probabilities
  • We print the input to verify correct data entry

Sum(value*probability) Over All Outcomes

In this step, you'll extend the previous program to calculate the expected value by computing the sum of each value multiplied by its probability.

Open the existing file and modify the code:

cd ~/project
nano expected_value.c

Update the code to calculate the expected value:

#include <stdio.h>

#define MAX_OUTCOMES 10

int main() {
    double values[MAX_OUTCOMES];
    double probabilities[MAX_OUTCOMES];
    int num_outcomes;
    double expected_value = 0.0;

    printf("Enter the number of outcomes (max %d): ", MAX_OUTCOMES);
    scanf("%d", &num_outcomes);

    // Input values
    printf("Enter the values:\n");
    for (int i = 0; i < num_outcomes; i++) {
        printf("Value %d: ", i + 1);
        scanf("%lf", &values[i]);
    }

    // Input probabilities
    printf("Enter the probabilities:\n");
    for (int i = 0; i < num_outcomes; i++) {
        printf("Probability %d: ", i + 1);
        scanf("%lf", &probabilities[i]);
    }

    // Calculate expected value
    for (int i = 0; i < num_outcomes; i++) {
        expected_value += values[i] * probabilities[i];
    }

    // Print results
    printf("\nCalculation Details:\n");
    for (int i = 0; i < num_outcomes; i++) {
        printf("Value %d: %.2f * Probability %d: %.2f = %.2f\n",
               i + 1, values[i], i + 1, probabilities[i],
               values[i] * probabilities[i]);
    }
    printf("\nExpected Value: %.2f\n", expected_value);

    return 0;
}

Compile and run the updated program:

gcc expected_value.c -o expected_value
./expected_value

Example output:

Enter the number of outcomes (max 10): 3
Enter the values:
Value 1: 10
Value 2: 20
Value 3: 30
Enter the probabilities:
Probability 1: 0.2
Probability 2: 0.5
Probability 3: 0.3

Calculation Details:
Value 1: 10.00 * Probability 1: 0.20 = 2.00
Value 2: 20.00 * Probability 2: 0.50 = 10.00
Value 3: 30.00 * Probability 3: 0.30 = 9.00

Expected Value: 21.00

Key points to understand:

  • We introduce expected_value to store the sum of value * probability
  • The for loop calculates each term and accumulates the total
  • We print detailed calculation steps to show how expected value is computed
  • Each outcome's contribution is shown as (value * probability)

Print the Expected Value

In this final step, you'll enhance the program to provide more detailed output and improve the user experience when displaying the expected value.

Open the existing file and make final modifications:

cd ~/project
nano expected_value.c

Update the code with improved formatting and error checking:

#include <stdio.h>

#define MAX_OUTCOMES 10

int main() {
    double values[MAX_OUTCOMES];
    double probabilities[MAX_OUTCOMES];
    int num_outcomes;
    double expected_value = 0.0;
    double total_probability = 0.0;

    printf("Expected Value Calculator\n");
    printf("========================\n");

    // Input number of outcomes
    do {
        printf("Enter the number of outcomes (1-%d): ", MAX_OUTCOMES);
        scanf("%d", &num_outcomes);

        if (num_outcomes < 1 || num_outcomes > MAX_OUTCOMES) {
            printf("Invalid number of outcomes. Please try again.\n");
        }
    } while (num_outcomes < 1 || num_outcomes > MAX_OUTCOMES);

    // Input values
    printf("\nEnter Values:\n");
    for (int i = 0; i < num_outcomes; i++) {
        printf("Value %d: ", i + 1);
        scanf("%lf", &values[i]);
    }

    // Input probabilities with validation
    printf("\nEnter Probabilities:\n");
    for (int i = 0; i < num_outcomes; i++) {
        printf("Probability %d: ", i + 1);
        scanf("%lf", &probabilities[i]);
        total_probability += probabilities[i];
    }

    // Validate total probability
    if (total_probability < 0.99 || total_probability > 1.01) {
        printf("\nWARNING: Probabilities do not sum to 1.0 (current sum: %.2f)\n",
               total_probability);
    }

    // Calculate expected value
    for (int i = 0; i < num_outcomes; i++) {
        expected_value += values[i] * probabilities[i];
    }

    // Print detailed results
    printf("\n--- Calculation Details ---\n");
    for (int i = 0; i < num_outcomes; i++) {
        printf("Outcome %d: Value = %.2f, Probability = %.2f\n",
               i + 1, values[i], probabilities[i]);
        printf("  Contribution: %.2f * %.2f = %.2f\n",
               values[i], probabilities[i], values[i] * probabilities[i]);
    }

    // Final expected value output
    printf("\n=== Expected Value ===\n");
    printf("E(X) = %.2f\n", expected_value);

    return 0;
}

Compile and run the final program:

gcc expected_value.c -o expected_value
./expected_value

Example output:

Expected Value Calculator
========================
Enter the number of outcomes (1-10): 3

Enter Values:
Value 1: 10
Value 2: 20
Value 3: 30

Enter Probabilities:
Probability 1: 0.2
Probability 2: 0.5
Probability 3: 0.3

--- Calculation Details ---
Outcome 1: Value = 10.00, Probability = 0.20
  Contribution: 10.00 * 0.20 = 2.00
Outcome 2: Value = 20.00, Probability = 0.50
  Contribution: 20.00 * 0.50 = 10.00
Outcome 3: Value = 30.00, Probability = 0.30
  Contribution: 30.00 * 0.30 = 9.00

=== Expected Value ===
E(X) = 21.00

Key improvements:

  • Added input validation for number of outcomes
  • Checked total probability sum
  • Enhanced output formatting
  • Showed individual outcome contributions
  • Clearly displayed the final expected value

Summary

In this lab, you will learn how to read values and probabilities, and then compute the expected value of a discrete distribution in C. First, you will create a program that allows users to input multiple values and their corresponding probabilities. Then, you will learn how to sum the product of each value and its probability to calculate the expected value. Finally, you will print the computed expected value.

The key points covered in this lab include using arrays to store values and probabilities, defining a maximum number of possible outcomes, and utilizing the scanf() function to read user input. The program ensures that the input values and probabilities are printed for verification before proceeding to the next step.

Other C Tutorials you may like