Friday, February 12, 2021

Finding The Mean Part II

A short while ago, I wrote a blog post called "Finding The Mean" where I gave code of a function I wrote which generates an array of n random real numbers between 0 and 1 inclusively. I wrote the function in Python, in R, and in GNU Octave. My goal was to write the function in as many programming languages as possible. I have now written a version in C.

I will be trying to write the same function in various other programming languages, probably including Ruby, Javascript, Scala, and many others, potentially in some functional programming languages like Haskell or SML (Standard ML). Stay tuned!

In passing, the main idea behind this program is the fact that as an array or list of random real numbers between 0 and 1 grows in size, the average will technically converge on 0.50. It's just a mathematical fact. I think it's called the Law of Large Numbers. "According to the law, the average of the results obtained from a large number of trials should be close to the expected value and will tend to become closer to the expected value as more trials are performed."

Here is a mathematical representation of the Law of Large Numbers:

ADDENDUM: Here is some Scala code that does the same thing, but only seems to work in the REPL. I'm not familiar enough with writing actual scala programs, but as I said it works in the REPL. Just change the value of n.

I was also able to translate the code into Ruby. This works in the REPL and worked as a simple Ruby program, though I think it lacks some of the usual formalism of Ruby programs. I tried to turn it into a function (via function definition) but it said there was an "undefined method", not recognizing the .sum method for arrays. But I got it to work in the following way, decomposed into different lines of code. You just have to change the value of n. Remember, this is all to prove the Law of Large Numbers:

The idea behind this proof of the Law of Large Numbers is simply that given an array of random real numbers (floats) between 0 and 1, the larger the length n of the array, the closer the mean of the values of the array will become to 0.50. That is, the mean of a large number of such random numbers, or the expected value, is 0.50. And if you try these functions with 10,000 or more values in the array, you'll see that it converges on 0.50. This is my so-called "proof" of the Law of Large Numbers.

No comments:

Post a Comment