Skip to content

Instantly share code, notes, and snippets.

@pat-hanbury
Last active August 1, 2022 09:54
Show Gist options
  • Save pat-hanbury/b2c028b1cd0336fb7501a144e84c01d5 to your computer and use it in GitHub Desktop.
Save pat-hanbury/b2c028b1cd0336fb7501a144e84c01d5 to your computer and use it in GitHub Desktop.
def get_crude_MC_variance(num_samples):
"""
This function returns the variance fo the Crude Monte Carlo.
Note that the inputed number of samples does not neccissarily
need to correspond to number of samples used in the Monte
Carlo Simulation.
Args:
- num_samples (int)
Return:
- Variance for Crude Monte Carlo approximation of f(x) (float)
"""
int_max = 5 # this is the max of our integration range
# get the average of squares
running_total = 0
for i in range(num_samples):
x = get_rand_number(0, int_max)
running_total += f_of_x(x)**2
sum_of_sqs = running_total*int_max / num_samples
# get square of average
running_total = 0
for i in range(num_samples):
x = get_rand_number(0, int_max)
running_total = f_of_x(x)
sq_ave = (int_max*running_total/num_samples)**2
return sum_of_sqs - sq_ave
@toneill818
Copy link

On line 25 is it supposed to be running_total += f_of_x(x)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment