Note
Go to the end to download the full example code.
Simple integralΒΆ
Calculation of a simple integral using Monte-Carlo integration.
Michel Bierlaire, EPFL Sat Jun 28 2025, 21:03:30
import pandas as pd
from biogeme.biogeme import BIOGEME
from biogeme.database import Database
from biogeme.expressions import Draws, MonteCarlo, exp
We create a fake database with one entry, as it is required to store the draws
df = pd.DataFrame()
df['FakeColumn'] = [1.0]
database = Database('fake_database', df)
integrand = exp(Draws('U', 'UNIFORM'))
simulated_integral = MonteCarlo(integrand)
true_integral = exp(1.0) - 1.0
R = 2_000
MULTIPLIER = 100_000
sample_variance = (
MonteCarlo(integrand * integrand) - simulated_integral * simulated_integral
)
stderr = (sample_variance / R) ** 0.5
error = simulated_integral - true_integral
simulate = {
'Analytical Integral': true_integral,
'Simulated Integral': simulated_integral,
'Sample variance ': sample_variance,
'Std Error ': stderr,
'Error ': error,
}
biosim = BIOGEME(database, simulate, number_of_draws=R)
R = biosim.number_of_draws
biosim.model_name = f'01simpleIntegral_{R}'
results = biosim.simulate(the_beta_values={})
print(f'Number of draws: {R}')
for c in results.columns:
print(f'{c}: {results.loc[0, c]}')
Number of draws: 2000
Analytical Integral: 1.718281828459045
Simulated Integral: 1.7073151237427406
Sample variance : 0.24465683877115685
Std Error : 0.01106021787242812
Error : -0.010966704716304454
Change the number of draws
biogeme2 = BIOGEME(database, simulate, number_of_draws=R * MULTIPLIER)
biogeme2.model_name = '01simpleIntegral_{multiplier*R}'
results2 = biogeme2.simulate(the_beta_values={})
print(f'Number of draws: {MULTIPLIER * R:_}')
for c in results2.columns:
print(f'{c}: {results2.loc[0, c]}')
Number of draws: 200_000_000
Analytical Integral: 1.718281828459045
Simulated Integral: 1.7181955668520812
Sample variance : 0.2420384267637878
Std Error : 0.011000873300874523
Error : -8.626160696389995e-05
Total running time of the script: (0 minutes 2.539 seconds)