Lab 1070 - e


In this lab, you will compute an approximation for the number e, which is approximately 2.718281828459045235. You will create an object called Random_e that has one accessor: getValue. The constructor itself will calculate the value of the number.

There are many ways to calculate the value for e other than by just typing it in or using a built-in constant. In this lab, your program will follow a simple algorithm. Here's how to think about it.

        1. set a sum to 0 
        2. choose a random number between 0 and 1 and add it to the sum. 
        3. if the sum is less than one, repeat step 2. 
        4. record how many times you had to do step 2.

Do this process over and over again, recording your answers to step 4, and the average of these answers should approach the number e.

Let's say on the first run, the random numbers were 0.3, 0.6 and 0.4 and it took those 3 numbers to add up to at least one. On the second run, it only took two numbers (0.9 and 0.4) and on the third run, it took three numbers. It took 3, then 2, then 3 numbers for the three trials, and the average is (3+2+3)/3 or about 2.66 which is already within 0.06 of the proper value after only three trials.


This lab is an exercise in being able to go from an algorithm to a working program. Write a class Test_e and a class Random_e to calculate an approximation to the number e using the algorithm described.

Copyright © 2010 by Asylum Computer Services LLC Return to CS Labs