import math
def det_2(r1c1,r1c2,r2c1,r2c2): #defining determinant of order 2
return r1c1*r2c2 - r1c2*r2c1
def area_q(x_1,y_1,x_2,y_2,x_3,y_3,x_4,y_4):
result = 0.5*(det_2(x_1,y_1,x_2,y_2)+det_2(x_2,y_2,x_3,y_3)+det_2(x_3,y_3,x_4,y_4)+det_2(x_4,y_4,x_1,y_1)) #area formula
return result
from matplotlib import pyplot as plt
def fn(x):
return math.sin(x) #input your function here.
x = []
count = 0.1 #used 0.1 instead of 0 to avoid zero division error eg- functions like sin(x)/x
a = 3.14159*6 #maximum limit on x
while count< a:
x.append(round((count),2)) #python float addition is not accurate, that is why round is used
count = count + 0.01 #to account for infinitesimal values which is the core of calculus,i.e., limit delta x tends to 0
y = []
start = 0
while start < len(x):
y.append( fn(x[start])) #plotting the curve
start = start + 1
y_d = []
j = 0
while j < len(x)-1:
y_d.append((fn(x[j]+x[j+1]-x[j])-fn(x[j]))/(x[j+1]-x[j])) #f'(x) = (f(x+dx)-f(x))/((x+dx)-x)
j = j+1
y_i = []
j = 0
while j <(len(x)-1): #at the terminal position quadrilateral cannot be formed, so it is excluded.
y_i.append(area_q(x[j],0,x[j+1],0,x[j+1],y[j+1],x[j],y[j]))#small area of quadrilateral
j = j+1
y_int = []
s = 0 #attempt to sum all small areas from x = 0 to x = s
while s <(len(x)-1):
t = 0
listf = []
while t <(s+1):
listf.append(y_i[t])
t = t+1
y_int.append(sum(listf))
s = s+1
plt.plot(x,y,color = 'red',label='original function')
plt.xlabel('x')
plt.ylabel('y=sin(x)')
x.remove(x[len(x)-1]) #to make number of elements in x and y_int same
plt.plot(x,y_int, color = 'blue',label='definite integration from 0 to x')
plt.plot(x,y_d, color = 'green', label = 'derivative')
plt.plot([0,a],[0,0],color = 'black')
plt.title('Integration & Differentiation')
plt.legend()
#plt.savefig('Sinx-i-d-graph.png')
plt.show()
 |
Output
|
Comments
Post a Comment