Random variables from one uniform distribution get added to create new rand var

Hi, all. I’m attempting to model what happens when random variables from one
distribution, specifically a uniform distribution, get added to create a new
random variable.
To begin with

begin
	ua = 2.0.*rand(10000) .- 1.0;
	histogram(ua,size=(300,300),leg=false)
end

Trying to do a running average of offset nearest elements to the right

temp[i]=ua[i+1] + ua[i+2] + ... + ua[i+offset]
	temp[i]=temp[i]/max(offset+1,1)

Could use function instead of another internal loop?
When initializing offset = 1 and plot a histogram of temp, i could use the values in temp, and then using the function normal(x,σ)=(1/sqrt(2pi*σ^2))exp(-x^2/(2*σ^2)) for the theoretical distribution, need to superimpose the curve of the theoretical normal distribution on the histogram of temp.

begin
	normal(x,σ)=(1/sqrt(2pi*σ^2))exp(-x^2/(2*σ^2))
	offset=4
	temp=zeros(length(ua))
	for i =1:?
		?
		?
	end
	histogram(temp,norm=true,size=(300,300),leg=false)
	σ2 = std(temp)
	plot!(x->normal(x,σ2),-1,1)
end

I’ve calculated the variance of 1/12. Know the standard deviation of a uniform distribution is (b-a)/sqrt(12) , However, cannot figure out for the life of me how to code for the theoretical standard deviation as a function of offset assuming independently drawn samples.

Welcome!

I’m not certain exactly what you are doing but the package Distributions might help. Here is a normal approximation to the sum of 3 uniform random variables.

using Plots, Distributions

n_vars = 3

n_samples = 10_000

dist = Uniform(0, 2)

samples = rand(dist, n_samples, n_vars)

sums = sum(samples, dims=2)

σ = sqrt(n_vars * var(dist))

μ = n_vars * mean(dist)

histogram(sums, leg=false, grid=false, norm=true)

x = 0:.1:6

dens = pdf.(Normal(μ, σ), x)

plot!(x, dens, color=:black, linestyle=:dash)

You can use var on a distribution object to obtain the variance. Note that adding or subtracting an offset does not change the variance. You might consider looking up the linearity of expectation and variance. I hope this gets you started in the right direction.

2 Likes

Sounds like you’re looking for cumsum?

You’re absolutely right. Just thinking about it logically, variance won’t change by shifting the graph. Your code works well, too, and makes sense as increasing n_vars changes the graph in the way expected. The way the notebook is put together doesn’t make the most sense for the Julia Language. Although, this is the first term Mathematica hasn’t been used for this course.

1 Like

Also, consider the excellent course on Introduction to Probabilities at the MITx: Probability - The Science of Uncertainty and Data

1 Like