Integrating a Simple Function
This is a simple exercise introducing the concept of Monte Carlo Integration.
Here we will evaluate a simple integral \( \int_0^1 x e^{x} dx\). We know that the exact answer is \(1\), but simulation will give us an approximate solution, so we can expect an answer close to \(1\). As we saw in the video, it's a simple process. For a function of a single variable \(f(x)\):
- Get the limits of the x-axis \((x_{min}, x_{max})\) and y-axis \((\max(f(x)), \min(\min(f(x)), 0))\).
- Generate a number of uniformly distributed point in this box.
- Multiply the area of the box (\((\max(f(x) - \min(f(x))\times(x_{max}-x_{min})\)) by the fraction of points that lie below \(f(x)\).
Upon completion, you will have a framework for handling definite integrals using Monte Carlo Integration.
Latihan ini adalah bagian dari kursus
Statistical Simulation in Python
Petunjuk latihan
- In the
sim_integrate()function, generate uniform random numbers betweenxminandxmaxand assign tox. - Generate uniform random numbers between \(\min(\min(f(x)), 0)\) and \(\max(f(x))\) and assign to
y. - Return the fraction of points less than \(f(x)\) multiplied by area (\((\max(f(x) - \min(f(x))\times(x_{max}-x_{min})\)) .
- Finally, use lambda function to define
funcas \(x e^{x}\).
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
# Define the sim_integrate function
def sim_integrate(func, xmin, xmax, sims):
x = np.random.uniform(____, ____, sims)
y = np.random.uniform(____, ____, sims)
area = (max(y) - min(y))*(xmax-xmin)
result = area * sum(____(____) < abs(func(x)))/sims
return result
# Call the sim_integrate function and print results
result = sim_integrate(func = lambda x: ____, xmin = 0, xmax = 1, sims = 50)
print("Simulated answer = {}, Actual Answer = 1".format(result))