dinky python ws 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

WORKSHEET 3

Student Name: Shagun Sharma UID: 22BCS11241


Branch: CSE Section/Group: 22BCS TPP 613 B
Semester: 4 Date of Performance:29-03-2024
Subject Name: Numerical Methods Subject Code: 22CSH-259
and Optimization using Python

1. Aim:
Implement the composite simpson' s 1/3 integration rue to numerically evaluate the integral
x sin(x) dx from 0 to pi using n=8 equally spaced subintervals . Print the approximate value
of the integral from your implementation.

2. Source Code:
import numpy as np
def f(x):
return x * np.sin(x)

def composite_simpsons_one_third(f, a, b, n):


if n % 2 != 0:
raise ValueError("n must be an even number")

h = (b - a) / n
x = np.linspace(a, b, n+1)
y = f(x)
integral = y[0] + y[n] # First and last terms
for i in range(1, n, 2): # Odd terms
integral += 4 * y[i]
for i in range(2, n-1, 2): # Even terms
integral += 2 * y[i]
integral *= h / 3
return integral
a=0
b = np.pi
n=8
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

approx_integral = composite_simpsons_one_third(f, a, b, n)

print("Approximate value of the integral:", approx_integral)

2. Screenshot of Outputs:

3. Learning Outcomes:
1. Understanding of numerical integration techniques.
2. Proficiency in implementing numerical methods in Python.
3. Ability to evaluate functions at multiple points using arrays.
4. Knowledge of error handling and input validation.
5. Application of numerical methods to real-world problems.

You might also like