You are on page 1of 5

keyboard_arrow_down INDIAN INSTITUTE OF INFORMATION TECHNOLOGY (IIIT) KOTTAYAM

Second Assignment, March, 2024 S6 BATCH 2:

ISC321 High Performance and Scientific Computing

keyboard_arrow_down NAME: USHA SREE VASI


ROLL NO: 2021BCS0022

1 Using four significant figures in the computations, (a)Write a program to determine 𝑑(sin(𝑥))⁄𝑑𝑥 at x =0.2 from the forward difference
approximation for 0 ≤ 𝑥 ≤ 1. (b)Write a program to determine 𝑑(𝑐𝑜𝑠(𝑥))⁄𝑑𝑥 at x =0.8 from the backward difference approximation for 0 ≤ 𝑥 ≤ 1.
Deduct insights about the value of h that gives the most accurate result. (This requires experimentation). Assume suitable values if required.

import math
import matplotlib.pyplot as plt

# Function to calculate the derivative of sin(x) using forward difference approximation


def forward_difference_sin(x, h):
return (math.sin(x + h) - math.sin(x)) / h

# Function to calculate the derivative of cos(x) using backward difference approximation


def backward_difference_cos(x, h):
return (math.cos(x) - math.cos(x - h)) / h

# (a) Determine derivative of sin(x) at x = 0.2 using forward difference approximation


def experiment_forward_difference():
x = 0.2
h_values = [0.1, 0.01, 0.001, 0.0001]
derivative_values = [forward_difference_sin(x, h) for h in h_values]

plt.plot(h_values, derivative_values, marker='o')


plt.title("Forward Difference Approximation for Derivative of sin(x)")
plt.xlabel("h")
plt.ylabel("Derivative of sin(x)")
plt.xscale('log') # Using log scale for better visualization
plt.grid(True)
plt.show()

# (b) Determine derivative of cos(x) at x = 0.8 using backward difference approximation


def experiment_backward_difference():
x = 0.8
h_values = [0.1, 0.01, 0.001, 0.0001]
derivative_values = [backward_difference_cos(x, h) for h in h_values]

plt.plot(h_values, derivative_values, marker='o')


plt.title("Backward Difference Approximation for Derivative of cos(x)")
plt.xlabel("h")
plt.ylabel("Derivative of cos(x)")
plt.xscale('log') # Using log scale for better visualization
plt.grid(True)
plt.show()

# Experimenting with different values of h


print("Experimenting with forward difference approximation:")
experiment_forward_difference()

print("\nExperimenting with backward difference approximation:")


experiment_backward_difference()
output Experimenting with forward difference approximation:

Experimenting with backward difference approximation:

You might also like