#!/usr/bin/python3 #-*- coding: Utf-8 -*- import random, math def monteCarlo(f, a, b, n): return sum([f(random.uniform(a, b)) for i in range(n)]) * (b - a) / n def pointMilieu(f, a, b, n): return sum([f(a + (i + 0.5) * (b - a) / n) for i in range(n)]) * (b - a) / n f = lambda x : 1 / x print('-'*80) print('{0:>10s} | {1:^14s} | {2:^14s} | {3:^14s} | {4:^14s} |'.format('n', 'Monte Carlo', 'erreur absolue', 'Point Milieu', 'erreur absolue')) print('-'*80) for i in range(0, 6): n = 10**i mc = monteCarlo(f, 1, 2, n) pm = pointMilieu(f, 1, 2, n) erreur_mc = math.log(2) - mc erreur_pm = math.log(2) - pm print('{0:10d} | {1: 14.10f} | {2: 14.10f} | {3: 14.10f} | {4: 14.10f} |' .format(n, mc, erreur_mc, pm, erreur_pm)) print('-'*80)