-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ.5 Class Integrate()
72 lines (60 loc) · 2.69 KB
/
Q.5 Class Integrate()
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
64
65
66
67
68
69
70
71
72
#Q.5
>>> class Integrate():
#a is the lower limit of integration
#b is the upper limit of integration
#n is the number of divisions and more the number of divisions,more is the accuracy
#fn is the function whose integration has to be done
#method : 1.Trapezoidal Rule 2.Simpsons Rule
#input : a,b,n,fn
def TrapezoidalRule(a,b,n,fn): #Method:1,function.1
sol=fn(a)
for i in range(1,n):
sol=sol+2*fn(a+(i*(b-a))/n)
sol=sol+fn(b)
sol=(sol*(b-a))/(2*n) #We evalute the value needed.
return sol #Now it's time to return this value.
def SimpsonsRule(a,b,n,fn): #Method:2,function.2
sol=fn(a)
for i in range(1,n,2):
sol=sol+ 4*fn(a+(i*(b-a))/n)
for i in range(2,n,2):
sol=sol+ 2*fn(a+(i*(b-a))/n)
sol=sol+fn(b)
sol=(sol*(b-a))/(3*n) #We evalute the value needed.
return sol #Now it's time to return this value.
def solve(self,a,b,n,fn,method): #solve() function :that calls either of the two above functions according to the input method.
if(method=='trapezoid'):
sol=TrapezoidalRule(a,b,n,fn)
return sol
if(method=='simpson'):
sol=SimpsonsRule(a,b,n,fn)
return sol
def plot(self,a,b,n,fn):
import matplotlib.pyplot as plt #importing matpltlib.pyplot
from numpy import arange
x=[i for i in arange(a,b,(b-a)/(n*1000.0))] #making a list of very close values of x(x-axis) in interval 'a' to 'b'
x=x+[b] #including value 'b' in list 'x'
y=[i for i in arange(a,b,(b-a)/(n*1.0))] #making list of values of x(x-axis) to make trapezium
y=y+[b] #including value 'b' in list 'y'
z=[fn(i) for i in x] #making a list of 'function-value' corresponding to x-axis value from list 'x'
plt.plot(x,z) #ploting the curve firstly
for i in range(n+1):
plt.plot([y[i],y[i]],[0,fn(y[i])]) #ploting the parallel sides of the trapezium
for i in range(n):
plt.plot([y[i],y[i+1]],[fn(y[i]),fn(y[i+1])]) #ploting the non-parallel side of trapezium
plt.show() #Finally showing the output graph
#Initial Example:
>>> f=lambda x:x*x
>>> igr=Integrate()
>>> for method in ['trapezoid','simpson']:
solution=igr.solve(1,6,100,f,method)
print(solution)
71.66875
71.66666666666666
#New Example:
>>> f=lambda: x:x**3
>>> igr=Integrate()
>>> a,b,n=2,7,15
>>> igr.plot(a,b,n,f)
##After pressing Enter the plot comes over the screen##
#Different trapezoid regions can be clearly distinguished