I'm writing a program that calculates the expected value of the sum of two discrete random variables. Here is the code:
EX = 0
EY = 0
X_number=int(input("Enter the number of possible values for X: "))
print("Enter ", X_number, " values of X and their probabilities. Press enter after each pair: ")
for i in range(X_number):
value, prob = input().split()
EX += float(value)*float(prob)
Y_number = int(input("\nEnter the number of possible values for Y: "))
print("Enter", Y_number, "values of Y and their probabilities. Press enter after each pair: ")
for i in range(Y_number):
value, prob = input().split()
EY += float(value)*float(prob)
print("\nE(X) = ", EX)
print("E(Y) = ", EY)
print("E(X+Y) = ", EX+EY)
The program works fine, but sometimes I see strange small inaccuracies in the numbers, which miraculously disappear in later results during the same run, e.g for data:
Enter the number of possible values for X: 3
Enter 3 values of X and their probabilities. Press enter after each pair:
9 0.3
3 0.5
-7 0.2
Enter the number of possible values for Y: 2
Enter 2 values of Y and their probabilities. Press enter after each pair:
100 0.9
-50 0.1
I get
E(X) = 2.799999999999999
E(Y) = 85.0
E(X+Y) = 87.8
I've read that this is due to the binary exponential storing of float in the computer, but such inaccuracies when dealing with numbers with only one decimal place aren't good, either :( Also, I have been using double
in C++ a lot on numbers with 3-4 decimal places and everything was always accurate, so I'm disappointed by Python here. Please tell me how to fix this. The program is simple, so I prefer not to use numpy
and other advanced stuff. Maybe a switch to fixed-point will do, as I only need 4-5 decimal places?