-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12-Monte_carlo_integral.py
63 lines (47 loc) · 1.26 KB
/
12-Monte_carlo_integral.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# -*- coding: utf-8 -*-
"""SM_Assignment-3.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1HNJYPctuKhf6dVEk8aSbCObqr4nmQEdH
"""
import math
import random
import matplotlib.pyplot as plt
trials=[100,1000,5000,10000]
#f(x)=x^2 e^x ln(x) 0-2
error_list=[]
for i in trials:
a=0
b=2
#print("Trials",i)
print("--------")
func_value=0
func_sum=0
func_squre_sum=0
func_avg=0
func_squard_avg=0
integral_value=0
error=0
for j in range(i):
x=random.uniform(a, b)
func_value=(x**2)*(math.exp(x))*(math.log(x))
func_sum=func_sum+func_value
func_squre=func_value**2
func_squre_sum=func_squre_sum+func_squre
func_avg=func_sum/i
func_squard_avg=func_squre_sum/i
integral_value=(b-a)*func_avg
error= ((b-a)/math.sqrt(i))*(math.sqrt(func_squard_avg-(func_avg**2)))
error_list.append(error)
print("For Points",i)
print("Integral Value",integral_value)
print("Error",error)
print("Error",error_list)
plt.figure(figsize=(8, 6))
x=["100","1000","5000","10000"]
#plt.ylim(0, 100)
plt.bar(x,error_list, tick_label = x, width = 0.2, color = ['steelblue'])
plt.xlabel('Number of trials')
plt.ylabel('Error')
plt.title('Error vs Number of trials')
plt.show()