Skip to content Skip to sidebar Skip to footer

Monte Carlo In 8 Dimensions Not Giving Correct Answer

I've been trying to compute the integral of (10*6)*sin(x0+x1+x2+x3+x4+x5+x6+x7)dx0dx1dx2dx3dx4dx5dx6dx7 using Monte-Carlo methods as part of my computing coursework at uni. I've m

Solution 1:

This codes converges to your analytical answer. I've made it more compact by generating all the samples in one go. Basically, you generate a matrix of random numbers and each row is one sample.

a=0#Defining Limits of Integration
b=(np.pi)/8
N=200000#Number of random numbers generated in each dimension

samples = np.random.uniform(a,b,(N,8))

deffunc(x):  #Defining the integrandreturn (10**6)*np.sin(np.sum(x))

integral = 0.0for i inrange(N):
    integral += func(samples[i,:])

answer=(((b-a)**8)/N)*integral
print ('The Integral is:', answer)

EDIT: Faster more efficient version

a=0          #Defining Limits of Integration
b=(np.pi)/8
N=2000000    #Number of random numbers generated in each dimension

samples = np.random.uniform(a,b,(N,8))

integrand_all_samples = (10**6)*np.sin(np.sum(samples, axis=1))
sum_all_samples = np.sum(integrand_all_samples)


answer=(((b-a)**8)/N)*sum_all_samples
print ('The Integral is:', answer)

EDIT 2: What is going wrong

The problematic code can be reduced to:

N=4

a,b = [[0]*N]*2# [[0]*N]*2: [[0,0,0,0],[0,0,0,0]]# a: [0,0,0,0]# b: [0,0,0,0]for i inrange(N):
    a[i]= 1
    b[i] = 2# a: [2,2,2,2]# b: [2,2,2,2]

a and b are pointing to the same list in memory despite having the different names. You can check this by looking at the output of id(a) and id(b). You truly only have one list. You can find the details of why here: List of lists changes reflected across sublists unexpectedly

Post a Comment for "Monte Carlo In 8 Dimensions Not Giving Correct Answer"