You are on page 1of 5

Lab 6

Question 1
Trapezoidal rule
Observation:
As we increase the value of n our answer will be more accurate.
Input:

lower_limit = 4
upper_limit = 5.2
n = 50

Code:
import numpy as np

# Function to integrate
def f(x):
return np.log(x)

# Implementing trapezoidal method


def trapezoidal(x0, xn, n):

# Value of h
h = (xn - x0) / n

# Finding sum
integration = f(x0) + f(xn)

for i in range(1, n):


k = x0 + i*h
integration = integration + 2 * f(k)

# Final integration value


integration = integration * h/2

return integration

# Input section
lower_limit = 4
upper_limit = 5.2
n = 50

# Call trapezoidal() method and get result


result = trapezoidal(lower_limit, upper_limit, n)
print("Integration result by Trapezoidal method is: %0.6
f" % (result))

Output:
Integration result by Trapezoidal method is: 1.827845

Simpson’s 1/3 Rule


Observation:
As we increase the value of n our answer will be more accurate.
Input:

lower_limit = 4
upper_limit = 5.2
n = 50

Code:
import numpy as np

def func(x):
return np.log(x)
def approximate_integral(lower_limit, upper_limit, n):

# Value of h
h = (upper_limit - lower_limit)/n

# Storing value of x and f(x)


x = list()
fx = list()

# Calcuting x and f(x)


i = 0
while i <= n:
x.append(lower_limit + i * h)
fx.append(func(x[i]))
i += 1

# Calculating result
result = 0
i = 0
for i in range(0, n+1):
if i == 0 or i == n:
result += fx[i]
elif i % 2 != 0:
result += 4 * fx[i]
else:
result += 2 * fx[i]

result = result * (h / 3)
return result

# Driver code
lower_limit = 4
upper_limit = 5.2
n = 50
print("%.6f" % approximate_integral(lower_limit, upper_l
imit, n))
Output:
Integration result by Simpson’s 1/3 Rule is: 1.827847
Question 2
Input:

def func(x):
return np.log(x)
lower_limit = 4.0
upper_limit = 5.2

Code:
import numpy as np

# Function to integrate

def integrate(function, a, b):


coeff = [7, 32, 12, 32, 7]
result = 0
for i in range(0, len(coeff)):
x = a + (i*(b-a))/(len(coeff)-1)
result += coeff[i]*function(x)
result = result*((b-a)/90.)
return result

def func(x):
return np.log(x)
lower_limit = 4.0
upper_limit = 5.2
print("""Integration result by Newton-
Cotes numerical integration formula is: %0.6f""" %
(integrate(func, lower_limit, upper_limit)))
Output:

Integration result by Newton-Cotes numerical integration


formula is: 1.827847

You might also like