0% found this document useful (0 votes)
13 views50 pages

GNUPlot & Python Practical Exam Guide

Uploaded by

suiujjh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views50 pages

GNUPlot & Python Practical Exam Guide

Uploaded by

suiujjh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

GNUPlot and Python - Comprehensive

Practical Exam Guide

WBSU/CU Physics Honours Syllabus (DS1-Lab /


Mathematical Methods-I Lab)

TABLE OF CONTENTS

1. Introduction & Course Overview


2. GNUPlot - Complete Guide
3. Python Programming - Complete Guide
4. Practical Problems with Solutions
5. Code Examples with Explanations
6. Practice Exam Questions
7. Important Functions Reference

SECTION 1: COURSE OVERVIEW

Credit Distribution

Course Code: PHSDSC101P (WBSU NEP) / DS1-Lab (CU)


Credits: 2 Credits
Total Hours: 60 Lectures/Classes
Evaluation: Internal Practical Exam (50%) + Viva (25%) + Assignments (25%)

Learning Outcomes

Students will be able to:

1. Visualize functions and data using GNUPlot


2. Write Python programs for numerical calculations
3. Implement numerical methods (Newton-Raphson, Least Squares Fitting,
Euler's Method)
4. Solve physical problems using computational methods
5. Create publication-quality graphs and visualizations

Assessment Criteria for Practical Exam

Code Quality: Logic, syntax, proper documentation


Output: Correct results, properly formatted
Visualization: Graphs with proper labels, titles, legends
Problem-Solving: Mathematical understanding demonstrated
Viva Questions: Understanding of code, methodology, physical concepts

SECTION 2: GNUPlot - COMPLETE GUIDE

2.1 Introduction to GNUPlot

What is GNUPlot?

Free, open-source graphing utility


Interactive and script-based plotting
Used for 2D, 3D, parametric, and polar plots
Exports to multiple formats (PNG, PDF, EPS, SVG)
Widely used in physics for data visualization

Why Use GNUPlot?

Lightweight and fast


No GUI overhead
Script-based (reproducible)
Excellent for fitting data
Publication-quality output
Suitable for batch processing

2.2 Basic GNUPlot Commands


Starting GNUPlot

gnuplot

Exiting GNUPlot

quit
exit

Plotting a Simple Function

plot sin(x)
plot cos(x)
plot x**2
plot exp(-x)

2.3 Essential GNUPlot Commands

1. Set Commands (Configuration)


# Set X and Y axis ranges
set xrange [-10:10]
set yrange [-2:2]

# Set axis labels


set xlabel "Time (seconds)"
set ylabel "Displacement (meters)"
set zlabel "Force (Newtons)"

# Set title
set title "Motion of a Harmonic Oscillator"

# Set grid
set grid

# Set output to file


set terminal png
set output "[Link]"

# Set line style


set style data lines
set style data points
set style data linespoints

# Set samples (resolution)


set samples 500

2. Plotting Functions
# Single function
plot sin(x)

# Multiple functions
plot sin(x), cos(x), tan(x)

# With line properties


plot sin(x) with lines linewidth 2 linecolor red
plot cos(x) with points pointsize 1.5
plot tan(x) with linespoints

# Using title (legend)


plot sin(x) title "y = sin(x)", cos(x) title "y = cos(x)"

# Line styles
plot sin(x) with lines linestyle 1 linewidth 2

Line Style Options:

with lines (w l) - solid line


with points (w p) - data points only
with dots (w d) - small dots
with linespoints (w lp) - lines and points
with impulses - vertical lines
with boxes - bar chart

Line Types (lt):

lt 1 - solid
lt 2 - dashed
lt 3 - dotted
lt 4 - dash-dot

Line Width (lw):


plot sin(x) w l lw 1 # thin line
plot sin(x) w l lw 3 # thick line
plot sin(x) w l lw 5 # very thick

Colors:

plot sin(x) linecolor red


plot cos(x) linecolor blue
plot tan(x) linecolor green
plot x**2 linecolor rgb "#FF00FF" # Magenta using hex code

3. Plotting from Data Files

First, create a data file [Link]:

#X Y1 Y2
0 0 0
1 1 1
2 4 2.718
3 9 20.09
4 16 54.60
5 25 148.41

Then plot it:


# Plot using columns 1 and 2
plot "[Link]" using 1:2 with points title "Data 1"

# Plot multiple columns from same file


plot "[Link]" using 1:2 with lines title "Series 1", \
"[Link]" using 1:3 with lines title "Series 2"

# Skip header lines (if any)


plot "[Link]" using 1:2 skip 1 with points

# Using every nth point


plot "[Link]" using 1:2 every 2 with linespoints

4. User-Defined Functions

# Define a function
f(x) = sin(x) * exp(-x/10)
g(x) = x**2 + 3*x + 2
h(x) = (x > 0) ? x**2 : -x**2 # Ternary operator (conditional)

# Plot the functions


plot f(x), g(x), h(x)

# Define with parameters


a=2
b=3
line(x) = a*x + b
plot line(x) title sprintf("y = %.2f*x + %.2f", a, b)

Useful Built-in Functions:

sin(x), cos(x), tan(x) - trigonometric


exp(x), log(x), log10(x) - exponential and logarithmic
sqrt(x) - square root
abs(x) - absolute value
int(x) - integer part
floor(x), ceil(x) - rounding
max(a,b), min(a,b) - maximum/minimum

5. Fitting Data

Fitting is crucial for analyzing experimental data.

# Define fit function


f(x) = a*x + b

# Perform fit
fit f(x) "[Link]" using 1:2 via a,b

# Results are printed showing fitted parameters and errors


# Output: a = 3.5 +/- 0.1, b = 0.2 +/- 0.05

# Plot both data and fit


plot "[Link]" with points title "Experimental Data", \
f(x) with lines title "Linear Fit"

Non-linear Fitting Example:

# Exponential fit: y = A*exp(B*x)


g(x) = A*exp(B*x)
fit g(x) "[Link]" using 1:2 via A, B

# Power law fit: y = A*x**B


h(x) = A*x**B
fit h(x) "[Link]" using 1:2 via A, B

6. 2D Parametric Plots
# Circle
set parametric
plot sin(t), cos(t) title "Circle"

# Spiral
plot t*sin(t), t*cos(t) title "Spiral"

# Lissajous figure: x = sin(3t), y = sin(2t)


set xrange [-1.5:1.5]
set yrange [-1.5:1.5]
plot sin(3*t), sin(2*t) title "Lissajous"
unset parametric

7. Polar Plots

# Switch to polar mode


set polar

# Plot in polar coordinates: r(theta)


set trange [0:2*pi]
plot sin(3*t) title "Rose Curve"
plot 1 + cos(t) title "Cardioid"

# Return to Cartesian
unset polar

2.4 GNUPlot Script Files

Creating a script file (e.g., [Link]):


# [Link] - Complete plotting script

# Terminal and output


set terminal png size 800,600
set output "harmonic_oscillator.png"

# Labels and title


set title "Harmonic Oscillator Motion" font ",16"
set xlabel "Time (s)" font ",12"
set ylabel "Displacement (m)" font ",12"

# Grid and ranges


set grid
set xrange [0:10]
set yrange [-1.5:1.5]

# Set key (legend) position


set key top right

# Samples for smooth curve


set samples 1000

# Define functions
omega = 2*pi # Angular frequency
A = 1.0 # Amplitude
phi = 0 # Phase

# Position as function of time


x(t) = A * sin(omega*t + phi)

# Plot
plot x(t) with lines linewidth 2 linecolor blue title "x(t) = sin(2Ï€t)", \
A*exp(-0.1*t)*sin(omega*t) with lines linewidth 2 linecolor red title "Damped: x(t) = exp(-0.1t)sin(2Ï€

# Reset
unset output
set terminal x11

Running the script:


gnuplot [Link]

2.5 Important GNUPlot Examples

Example 1: Pendulum Motion

set title "Pendulum Motion"


set xlabel "Time (s)"
set ylabel "Angle (radians)"
set xrange [0:10]
set grid
plot sin(t)*exp(-0.05*t) with lines title "θ(t) = sin(t)e^(-0.05t)"

Example 2: Projectile Trajectory


# Projectile with initial velocity 20 m/s at 45 degrees
# x(t) = v0*cos(θ)*t
# y(t) = v0*sin(θ)*t - 0.5*g*t^2

v0 = 20
theta = pi/4
g = 9.81

x(t) = v0*cos(theta)*t
y(t) = v0*sin(theta)*t - 0.5*g*t**2

set parametric
set xlabel "Horizontal Distance (m)"
set ylabel "Height (m)"
set title "Projectile Trajectory"
plot x(t), y(t) with lines linewidth 2

Example 3: Fitting Temperature vs Time Data

# Newton's Law of Cooling: T(t) = Tenv + (T0 - Tenv)*exp(-k*t)

T_env = 25 # Environment temperature


k = 0.1 # Cooling constant

f(t) = T_env + (100 - T_env)*exp(-k*t)

set title "Newton's Law of Cooling"


set xlabel "Time (minutes)"
set ylabel "Temperature (°C)"
plot "[Link]" with points title "Experimental Data", \
f(t) with lines title "Theoretical Model"

SECTION 3: PYTHON PROGRAMMING - COMPLETE


GUIDE

3.1 Python Basics

Starting Python

python3
# or
python

# Exit
exit()
# or
quit()

Python as a Calculator

2+3 #5
10 - 4 #6
3*7 # 21
20 / 5 # 4.0
2 ** 10 # 1024 (exponentiation)
17 % 5 # 2 (modulus)

3.2 Variables and Data Types


# Integers
a = 10
b = -5
c=0

# Floating point
x = 3.14
y = 2.71828
z = 1.0

# Strings
name = "Physics"
message = 'Hello, World!'

# Boolean
is_positive = True
is_even = False

# Type checking
type(a) # <class 'int'>
type(x) # <class 'float'>
type(name) # <class 'str'>
type(is_positive) # <class 'bool'>

# Type conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(1) # True
bool(0) # False

3.3 List, Tuple, and String Operations

Lists
# Creating lists
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True]
empty = []

# Indexing (0-based)
first = numbers[0] #1
last = numbers[-1] #5
second_from_end = numbers[-2] # 4

# Slicing
numbers[1:3] # [2, 3]
numbers[:3] # [1, 2, 3]
numbers[2:] # [3, 4, 5]
numbers[::2] # [1, 3, 5] (every 2nd element)
numbers[::-1] # [5, 4, 3, 2, 1] (reversed)

# List methods
[Link](6) # Add element: [1,2,3,4,5,6]
[Link]([7, 8]) # Add multiple: [1,2,3,4,5,6,7,8]
[Link](0, 0) # Insert at position
[Link](3) # Remove first occurrence of 3
[Link]() # Remove and return last element
[Link](0) # Remove and return first element
[Link]() # Sort in-place
sorted(numbers) # Return sorted copy
[Link]() # Reverse in-place
[Link](2) # Count occurrences of 2
[Link](4) # Find index of 4
len(numbers) # Length: 5

# List comprehension
squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25]
evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, ..., 18]

Tuples
# Creating tuples
point = (3, 4)
rgb = (255, 128, 0)
single = (42,) # Note comma for single element

# Tuple operations (read-only)


x, y = point # Unpacking
a, b, c = rgb

# Tuples as function return values


def get_coordinates():
return (10, 20)

x, y = get_coordinates()

# Packing and unpacking


a, b = 1, 2 # Packing
b, a = a, b # Swapping variables

Strings
# String creation
s1 = "Hello"
s2 = 'World'
s3 = """Multi-line
string here"""

# String indexing and slicing


s = "Python"
s[0] # 'P'
s[-1] # 'n'
s[1:4] # 'yth'

# String methods
[Link]() # 'PYTHON'
[Link]() # 'python'
[Link]() # 'Python'
[Link]('Py') # True
[Link]('on') # True
[Link]('th') #2
[Link]('Python', 'Java') # 'Java'
[Link]() # ['Python']
' '.join(['a', 'b', 'c']) # 'a b c'
[Link]() # Remove leading/trailing whitespace
len(s) #6

# String formatting
name = "Alice"
age = 25
f"My name is {name} and I'm {age}" # f-string (recommended)
"My name is {} and I'm {}".format(name, age) # Old style

3.4 Control Flow

If-Elif-Else
x = 15

if x < 0:
print("Negative")
elif x == 0:
print("Zero")
else:
print("Positive")

# Comparison operators
x == y # Equal
x != y # Not equal
x<y # Less than
x <= y # Less than or equal
x>y # Greater than
x >= y # Greater than or equal

# Logical operators
if x > 0 and x < 10:
print("Between 0 and 10")

if x < 0 or x > 100:


print("Out of range")

if not (x == 5):
print("Not equal to 5")

# Ternary operator
result = "Positive" if x > 0 else "Non-positive"

Loops

For Loop:
# Loop through range
for i in range(5): # 0, 1, 2, 3, 4
print(i)

for i in range(1, 6): # 1, 2, 3, 4, 5


print(i)

for i in range(0, 10, 2): # 0, 2, 4, 6, 8


print(i)

# Loop through list


for item in [10, 20, 30]:
print(item)

# Loop with enumerate (get index and value)


for idx, value in enumerate(['a', 'b', 'c']):
print(f"Index {idx}: {value}")

# Loop through dictionary


d = {'name': 'Alice', 'age': 25}
for key, value in [Link]():
print(f"{key}: {value}")

# Nested loops
for i in range(3):
for j in range(3):
print(f"({i},{j})", end=" ")
print() # New line

While Loop:
# Simple while loop
i=0
while i < 5:
print(i)
i += 1

# While with break


while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
print(f"You said: {user_input}")

# While with continue


i=0
while i < 10:
i += 1
if i % 2 == 0:
continue # Skip even numbers
print(i) # Only odd: 1, 3, 5, 7, 9

3.5 Functions

# Simple function
def greet(name):
print(f"Hello, {name}!")

greet("Alice")

# Function with return value


def add(a, b):
return a + b

result = add(3, 5) #8

# Function with default arguments


def power(x, n=2):
return x ** n
power(2) # 4 (2^2)
power(2, 3) # 8 (2^3)

# Function with multiple returns


def get_statistics(numbers):
mean = sum(numbers) / len(numbers)
minimum = min(numbers)
maximum = max(numbers)
return mean, minimum, maximum

m, min_val, max_val = get_statistics([1, 2, 3, 4, 5])

# Function with *args (variable arguments)


def sum_all(*args):
total = 0
for num in args:
total += num
return total

sum_all(1, 2, 3, 4, 5) # 15

# Function with **kwargs (keyword arguments)


def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")

print_info(name="Alice", age=25, city="NYC")

# Lambda functions (anonymous functions)


square = lambda x: x ** 2
square(5) # 25

# Sorting with lambda


students = [("Alice", 25), ("Bob", 20), ("Charlie", 22)]
sorted(students, key=lambda x: x[1]) # Sort by age

3.6 Modules and Imports


# Import entire module
import math
[Link](0)
[Link]([Link])
[Link](16) #4
[Link](1) # e ≈ 2.718
[Link](10) # Natural log
math.log10(100) # Base 10 log
[Link](5) # 120

# Import specific function


from math import sin, cos, pi
sin(pi/2) #1
cos(0) #1

# Import with alias


import numpy as np # numpy (must be installed)
[Link]([1, 2, 3])

# Get help
help([Link])
dir(math) # List all functions in math

3.7 File Input/Output


# Writing to file
with open("[Link]", "w") as f:
[Link]("Temperature (°C)\tTime (min)\n")
[Link]("100\t0\n")
[Link]("95\t2\n")
[Link]("90\t4\n")

# Reading from file


with open("[Link]", "r") as f:
content = [Link]() # Read entire file
print(content)

# Reading line by line


with open("[Link]", "r") as f:
for line in f:
print([Link]())

# Reading into list


with open("[Link]", "r") as f:
lines = [Link]() # List of lines

# Appending to file
with open("[Link]", "a") as f:
[Link]("85\t6\n")

SECTION 4: PRACTICAL PROBLEMS WITH SOLUTIONS

PROBLEM 1: Quadratic Equation Solver

Mathematical Background: For equation $ax^2 + bx + c = 0$:

Discriminant: $\Delta = b^2 - 4ac$


Roots: $x = \frac{-b \pm \sqrt{\Delta}}{2a}$

Python Code:
import math

def solve_quadratic(a, b, c):


"""
Solve quadratic equation ax^2 + bx + c = 0
Returns tuple of roots or None if no real roots
"""
if a == 0:
if b == 0:
return None
return -c/b

discriminant = b**2 - 4*a*c

if discriminant < 0:
print("No real roots (complex roots exist)")
# Calculate complex roots
real_part = -b / (2*a)
imag_part = [Link](-discriminant) / (2*a)
return (real_part + imag_part*1j, real_part - imag_part*1j)

sqrt_delta = [Link](discriminant)
x1 = (-b + sqrt_delta) / (2*a)
x2 = (-b - sqrt_delta) / (2*a)

return x1, x2

# Example usage
a, b, c = 1, -5, 6 # x^2 - 5x + 6 = 0
roots = solve_quadratic(a, b, c)
print(f"Roots: {roots}") # (3.0, 2.0)

# Verify
a, b, c = 2, -7, 3 # 2x^2 - 7x + 3 = 0
x1, x2 = solve_quadratic(a, b, c)
print(f"x1 = {x1}, x2 = {x2}") # x1 = 3.0, x2 = 0.5

GNUPlot Visualization:
# File: [Link]
set title "Quadratic Equation: x^2 - 5x + 6 = 0"
set xlabel "x"
set ylabel "y"
set xrange [-1:6]
set grid
set yrange [-2:5]

f(x) = x**2 - 5*x + 6

# Plot parabola
plot f(x) with lines linewidth 2 title "f(x) = x^2 - 5x + 6"

# Mark roots
set label "Root 1: (2, 0)" at 2, 0.3
set label "Root 2: (3, 0)" at 3, 0.3

PROBLEM 2: Arithmetic and Geometric Progressions

Arithmetic Progression (AP):

General term: $a_n = a_1 + (n-1)d$


Sum: $S_n = \frac{n}{2}(2a_1 + (n-1)d) = \frac{n}{2}(a_1 + a_n)$

Geometric Progression (GP):

General term: $a_n = a_1 \cdot r^{n-1}$


Sum: $S_n = a_1 \cdot \frac{1-r^n}{1-r}$ (for $r \neq 1$)

Python Code:
def ap_nth_term(a1, d, n):
"""Find nth term of AP"""
return a1 + (n - 1) * d

def ap_sum(a1, d, n):


"""Find sum of first n terms of AP"""
return n * (2*a1 + (n-1)*d) / 2

def ap_sum_with_last(a1, an, n):


"""Sum using first and last terms"""
return n * (a1 + an) / 2

def gp_nth_term(a1, r, n):


"""Find nth term of GP"""
return a1 * (r ** (n - 1))

def gp_sum(a1, r, n):


"""Find sum of first n terms of GP"""
if r == 1:
return a1 * n
return a1 * (1 - r**n) / (1 - r)

# Example: AP with a1=2, d=3


print("AP: 2, 5, 8, 11, ...")
print(f"5th term: {ap_nth_term(2, 3, 5)}") # 14
print(f"Sum of 10 terms: {ap_sum(2, 3, 10)}") # 155

# Example: GP with a1=2, r=2


print("\nGP: 2, 4, 8, 16, ...")
print(f"5th term: {gp_nth_term(2, 2, 5)}") # 32
print(f"Sum of 10 terms: {gp_sum(2, 2, 10)}") # 2046

Plotting AP and GP:


import math

# Save AP terms to file


with open("ap_data.txt", "w") as f:
a1, d = 2, 3
for n in range(1, 11):
an = a1 + (n-1)*d
[Link](f"{n}\t{an}\n")

# Save GP terms to file


with open("gp_data.txt", "w") as f:
a1, r = 2, 1.5
for n in range(1, 11):
an = a1 * (r**(n-1))
[Link](f"{n}\t{an}\n")

GNUPlot Script:

set title "AP vs GP"


set xlabel "Term Number (n)"
set ylabel "Term Value"
set grid

plot "ap_data.txt" using 1:2 with points title "AP: 2, 5, 8, 11, ...", \
"gp_data.txt" using 1:2 with points title "GP: 2, 3, 4.5, 6.75, ..."

PROBLEM 3: Newton-Raphson Method

Purpose: Find roots of equation $f(x) = 0$

Formula: $$x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}$$

Algorithm:
1. Start with initial guess $x_0$
2. Iterate until convergence
3. Stop when $|f(x_n)| <$ tolerance or $|x_{n+1} - x_n| <$ tolerance

Python Code:

import math

def newton_raphson(f, df, x0, tol=1e-6, max_iter=100):


"""
Newton-Raphson method
f: function
df: derivative of function
x0: initial guess
tol: tolerance
max_iter: maximum iterations
"""
x = x0
iterations = []

for i in range(max_iter):
fx = f(x)
dfx = df(x)

if abs(dfx) < 1e-10:


print(f"Derivative too small at iteration {i}")
break

x_new = x - fx / dfx
[Link]((i+1, x, fx))

if abs(x_new - x) < tol:


print(f"Converged in {i+1} iterations")
return x_new, iterations

x = x_new

print(f"Did not converge after {max_iter} iterations")


return x, iterations

# Example 1: Find root of x^2 - 4 = 0 (should get x = 2)


def f1(x):
return x**2 - 4
return x**2 - 4

def df1(x):
return 2*x

root, history = newton_raphson(f1, df1, 3.0) # Start at x=3


print(f"Root of x^2 - 4 = 0: {root}") # ~2.0

# Example 2: Find root of x^3 - 2 = 0 (cube root of 2)


def f2(x):
return x**3 - 2

def df2(x):
return 3*x**2

root, history = newton_raphson(f2, df2, 1.5) # Start at x=1.5


print(f"Root of x^3 - 2 = 0: {root}") # ~1.2599...

# Save iteration history


with open("newton_history.txt", "w") as f:
[Link]("Iteration\tX\t\tF(X)\n")
for iter_num, x, fx in history:
[Link](f"{iter_num}\t{x:.10f}\t{fx:.2e}\n")

GNUPlot Visualization:
set title "Newton-Raphson Method: Finding Root of x^2 - 4 = 0"
set xlabel "x"
set ylabel "y"
set xrange [0:4]
set yrange [-5:12]
set grid

f(x) = x**2 - 4

# Plot function
plot f(x) with lines linewidth 2 title "f(x) = x^2 - 4", \
0 with lines linewidth 1 title "y = 0"

# Mark root
set label "Root = 2" at 2, -1

PROBLEM 4: Least Squares Fitting

Objective: Fit experimental data to a model

Linear Least Squares: Fit $y = ax + b$

Formulas: $$a = \frac{n\sum xy - \sum x \sum y}{n\sum x^2 - (\sum x)^2}$$ $$b
= \frac{\sum y - a\sum x}{n}$$

Python Code:

def linear_least_squares(x_data, y_data):


"""
Perform linear least squares fitting
Returns: (slope a, intercept b, correlation_coefficient R)
"""
n = len(x_data)

sum_x = sum(x_data)
sum_y = sum(y_data)
sum_xx = sum(x**2 for x in x_data)
sum_xx = sum(x**2 for x in x_data)
sum_xy = sum(x*y for x, y in zip(x_data, y_data))
sum_yy = sum(y**2 for y in y_data)

# Calculate slope and intercept


denominator = n*sum_xx - sum_x**2

if abs(denominator) < 1e-10:


print("Cannot fit: all x values are the same")
return None, None, None

a = (n*sum_xy - sum_x*sum_y) / denominator


b = (sum_y - a*sum_x) / n

# Calculate correlation coefficient


numerator = n*sum_xy - sum_x*sum_y
denominator_r = ((n*sum_xx - sum_x**2) * (n*sum_yy - sum_y**2))**0.5

if denominator_r == 0:
R=0
else:
R = numerator / denominator_r

return a, b, R

# Experimental data
x = [1, 2, 3, 4, 5]
y = [2.1, 4.2, 5.9, 8.1, 10.0]

a, b, R = linear_least_squares(x, y)
print(f"Fitted equation: y = {a:.3f}x + {b:.3f}")
print(f"Correlation coefficient R = {R:.4f}")

# Create data file and fit


with open("[Link]", "w") as f:
[Link]("# x\ty\n")
for xi, yi in zip(x, y):
[Link](f"{xi}\t{yi}\n")

# Save fit results


with open("fit_results.txt", "w") as f:
[Link](f"Linear Fit: y = ax + b\n")
[Link](f"Slope a = {a:.6f}\n")
[Link](f"Intercept b = {b:.6f}\n")
[Link](f"Correlation coefficient R = {R:.6f}\n")
GNUPlot Fitting:

# Fit data using gnuplot


f(x) = a*x + b
fit f(x) "[Link]" using 1:2 via a, b

set title "Linear Least Squares Fitting"


set xlabel "x"
set ylabel "y"
set grid

plot "[Link]" with points pointsize 1.5 title "Experimental Data", \


f(x) with lines linewidth 2 title sprintf("Fit: y = %.3f*x + %.3f", a, b)

PROBLEM 5: Projectile Motion using Euler's Method

Differential Equations: $$\frac{dv_x}{dt} = 0 \quad \Rightarrow \quad v_x =


v_0\cos\theta$$ $$\frac{dv_y}{dt} = -g \quad \Rightarrow \quad v_y(t) =
v_0\sin\theta - gt$$ $$\frac{dx}{dt} = v_x, \quad \frac{dy}{dt} = v_y$$

Euler's Method: $$x_{n+1} = x_n + v_x \cdot \Delta t$$ $$y_{n+1} = y_n + v_y
\cdot \Delta t$$ $$v_y^{(n+1)} = v_y^{(n)} - g \cdot \Delta t$$

Python Code:

import math

def projectile_motion_euler(v0, theta_deg, g=9.81, dt=0.01):


"""
Simulate projectile motion using Euler's method
v0: initial velocity (m/s)
theta_deg: launch angle (degrees)
g: gravitational acceleration (m/s^2)
dt: time step (seconds)
dt: time step (seconds)

Returns: lists of (t, x, y)


"""
theta = [Link](theta_deg)

# Initial conditions
vx = v0 * [Link](theta)
vy = v0 * [Link](theta)
x, y = 0, 0

trajectory = []
t=0

while y >= 0: # Until projectile hits ground


[Link]((t, x, y))

# Update velocities and positions


vy -= g * dt
x += vx * dt
y += vy * dt
t += dt

return trajectory

# Simulate projectile at 45 degrees with v0 = 20 m/s


trajectory = projectile_motion_euler(v0=20, theta_deg=45)

# Save to file
with open("[Link]", "w") as f:
[Link]("# Time(s)\tX(m)\t\tY(m)\n")
for t, x, y in trajectory:
[Link](f"{t:.2f}\t{x:.2f}\t\t{y:.2f}\n")

print(f"Range: {trajectory[-1][1]:.2f} m")


print(f"Flight time: {trajectory[-1][0]:.2f} s")

GNUPlot Visualization:
# File: [Link]
set title "Projectile Motion (v0=20 m/s, θ=45°)"
set xlabel "Horizontal Distance (m)"
set ylabel "Height (m)"
set grid

# Set aspect ratio


set size square

plot "[Link]" using 2:3 with lines linewidth 2 title "Trajectory"

PROBLEM 6: Matrix Operations

Python Code:

def matrix_add(A, B):


"""Add two matrices"""
if len(A) != len(B) or len(A[0]) != len(B[0]):
return None

result = []
for i in range(len(A)):
row = []
for j in range(len(A[0])):
[Link](A[i][j] + B[i][j])
[Link](row)

return result

def matrix_multiply(A, B):


"""Multiply two matrices A and B"""
if len(A[0]) != len(B):
print("Incompatible matrix dimensions for multiplication")
return None

result = []
for i in range(len(A)):
row = []
row = []
for j in range(len(B[0])):
sum_val = 0
for k in range(len(B)):
sum_val += A[i][k] * B[k][j]
[Link](sum_val)
[Link](row)

return result

def matrix_transpose(A):
"""Transpose matrix A"""
return [[A[i][j] for i in range(len(A))] for j in range(len(A[0]))]

def print_matrix(A, name="Matrix"):


"""Print matrix nicely"""
print(f"\n{name}:")
for row in A:
print([f"{val:.2f}" for val in row])

# Example
A = [[1, 2, 3],
[4, 5, 6]]

B = [[7, 8, 9],
[10, 11, 12]]

C = matrix_add(A, B)
print_matrix(C, "A + B")

D = matrix_transpose(A)
print_matrix(D, "A^T")

# Multiply A (2x3) by A^T (3x2) to get (2x2)


E = matrix_multiply(A, D)
print_matrix(E, "A × A^T")

SECTION 5: CODE EXAMPLES WITH DETAILED


EXPLANATIONS
Example 1: Prime Number Finder

Program: Generate all prime numbers up to N

def find_primes(n):
"""
Find all prime numbers up to n using Sieve of Eratosthenes

Algorithm:
1. Create list of consecutive integers from 2 to n
2. Mark multiples of each prime as composite
3. Return unmarked (prime) numbers
"""
if n < 2:
return []

is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False

for i in range(2, int(n**0.5) + 1):


if is_prime[i]:
# Mark all multiples of i as not prime
for j in range(i*i, n + 1, i):
is_prime[j] = False

# Return all indices where is_prime[i] is True


primes = [i for i in range(n + 1) if is_prime[i]]
return primes

# Example
primes = find_primes(100)
print(f"Primes up to 100: {primes}")
print(f"Count: {len(primes)}")

# Save to file
with open("[Link]", "w") as f:
[Link]("Prime Numbers up to 100\n")
for i, p in enumerate(primes):
[Link](f"{p}\n")
Example 2: Fibonacci Series

Program: Generate Fibonacci sequence


def fibonacci(n):
"""
Generate Fibonacci sequence with n terms
F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2)
"""
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]

fib = [0, 1]
for i in range(2, n):
[Link](fib[i-1] + fib[i-2])

return fib

def fibonacci_recursive(n):
"""Recursive approach (slower for large n)"""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)

# Generate Fibonacci numbers


fib_seq = fibonacci(15)
print(f"First 15 Fibonacci numbers: {fib_seq}")

# Calculate ratios (should approach golden ratio ≈ 1.618)


print("\nRatios of consecutive Fibonacci numbers (approach φ):")
for i in range(2, len(fib_seq)):
ratio = fib_seq[i] / fib_seq[i-1]
print(f"F({i+1})/F({i}) = {ratio:.6f}")

Example 3: Integration using Trapezoidal Rule


Program: Numerically integrate a function

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


"""
Numerically integrate f from a to b using trapezoidal rule

Formula: ∫f(x)dx ≈ (h/2)[f(a) + 2f(x1) + 2f(x2) + ... + 2f(xn-1) + f(b)]


where h = (b-a)/n
"""
h = (b - a) / n

# First and last terms


sum_val = (f(a) + f(b)) / 2

# Middle terms
for i in range(1, n):
x=a+i*h
sum_val += f(x)

integral = h * sum_val
return integral

# Example: Integrate sin(x) from 0 to π/2 (should get 1)


import math

def f(x):
return [Link](x)

a, b = 0, [Link]/2
for n in [10, 50, 100, 500]:
result = trapezoidal_rule(f, a, b, n)
error = abs(result - 1) # Exact answer is 1
print(f"n={n:3d}: Integral = {result:.8f}, Error = {error:.2e}")

SECTION 6: PRACTICE EXAM QUESTIONS

EXAM QUESTION 1: Temperature Decay


Question: The temperature of a cooling object follows Newton's Law of
Cooling: $$T(t) = T_{\infty} + (T_0 - T_{\infty})e^{-kt}$$

Given:

Initial temperature T₀ = 100°C


Environment temperature T∞ = 25°C
Cooling constant k = 0.1 minâ​»Â¹
Experimental data in cooling_data.txt

Tasks:

1. Write Python code to fit the data


2. Use GNUPlot to visualize both data and fit
3. Find the time when temperature drops to 50°C

Solution (Python):
import math

def cooling_law(t, T_inf, T0, k):


return T_inf + (T0 - T_inf) * [Link](-k*t)

def find_time_for_temp(T_target, T_inf, T0, k):


"""Find time when temperature equals T_target"""
# Solve: T_target = T_inf + (T0 - T_inf)*exp(-k*t)
# (T_target - T_inf) = (T0 - T_inf)*exp(-k*t)
# exp(-k*t) = (T_target - T_inf)/(T0 - T_inf)
# -k*t = ln(...)
# t = -ln(...)/k

ratio = (T_target - T_inf) / (T0 - T_inf)


if ratio <= 0:
return None

t = -[Link](ratio) / k
return t

T_inf = 25
T0 = 100
k = 0.1

# Time when temperature = 50°C


t_50 = find_time_for_temp(50, T_inf, T0, k)
print(f"Temperature reaches 50°C at t = {t_50:.2f} minutes")

# Generate theoretical curve


with open("theoretical_cooling.txt", "w") as f:
[Link]("Time(min)\tTemp(C)\n")
for t in range(0, 50):
T = cooling_law(t, T_inf, T0, k)
[Link](f"{t}\t{T:.2f}\n")

Solution (GNUPlot):
# Fit experimental data
T(t) = T_inf + (T0 - T_inf)*exp(-k*t)
T_inf = 25
T0 = 100
k = 0.1

fit T(t) "cooling_data.txt" using 1:2 via T_inf, T0, k

set title "Newton's Law of Cooling"


set xlabel "Time (minutes)"
set ylabel "Temperature (°C)"
set grid

plot "cooling_data.txt" with points title "Experimental Data", \


T(t) with lines title sprintf("Fit: T(t) = %.1f + %.1f*exp(-%.3f*t)", T_inf, T0-T_inf, k)

EXAM QUESTION 2: Harmonic Oscillator

Question: A mass on a spring exhibits simple harmonic motion: $$x(t) =


A\sin(\omega t + \phi)$$

Where:

A = 0.5 m (amplitude)
ω = 2π rad/s (angular frequency, f = 1 Hz)
φ = 0 (initial phase)

Tasks:

1. Generate position, velocity, and acceleration data


2. Plot all three on same graph
3. Verify energy conservation: E = ½kx² + ½mv² (with k/m = ω²)

Solution (Python):
import math

def harmonic_oscillator(A, omega, phi, t):


"""Position of harmonic oscillator"""
return A * [Link](omega * t + phi)

def velocity(A, omega, phi, t):


"""Velocity: v = dx/dt"""
return A * omega * [Link](omega * t + phi)

def acceleration(A, omega, phi, t):


"""Acceleration: a = d²x/dt²"""
return -A * omega**2 * [Link](omega * t + phi)

# Parameters
A = 0.5
omega = 2 * [Link]
phi = 0

# Generate data
with open("[Link]", "w") as f:
[Link]("Time(s)\tPosition(m)\tVelocity(m/s)\tAccel(m/s2)\tEnergy(J)\n")

m = 1.0 # mass (kg)


k = m * omega**2 # spring constant

for t in [i/100 for i in range(0, 200)]: # 0 to 2 seconds, step 0.01


x = harmonic_oscillator(A, omega, phi, t)
v = velocity(A, omega, phi, t)
a = acceleration(A, omega, phi, t)

# Energy
KE = 0.5 * m * v**2
PE = 0.5 * k * x**2
E_total = KE + PE

[Link](f"{t:.2f}\t{x:.6f}\t{v:.6f}\t{a:.6f}\t{E_total:.6f}\n")

print("Data saved to [Link]")


Solution (GNUPlot):

set title "Simple Harmonic Oscillator"


set xlabel "Time (s)"
set ylabel "Value"
set grid

# Use different y-axes for different scales


set y2label "Energy (J)"
set y2range [0:0.3]
set yrange [-1:1]

plot "[Link]" using 1:2 with lines axis x1y1 title "Position (m)", \
"[Link]" using 1:3 with lines axis x1y1 title "Velocity (m/s)", \
"[Link]" using 1:4 with lines axis x1y1 title "Acceleration (m/s²)", \
"[Link]" using 1:5 with lines axis x1y2 title "Energy (J)"

EXAM QUESTION 3: Root Finding with Multiple Methods

Question: Find the root of f(x) = x³ - 2x - 5 = 0 using:

1. Graphical method (plotting)


2. Newton-Raphson method
3. Bisection method

Solution (Python):

import math

def f(x):
return x**3 - 2*x - 5

def df(x):
return 3*x**2 - 2

# Bisection method
def bisection(f, a, b, tol=1e-6):
def bisection(f, a, b, tol=1e-6):
"""Find root using bisection method"""
iterations = []

while abs(b - a) > tol:


c = (a + b) / 2
[Link]((a, b, c, f(c)))

if f(a) * f(c) < 0:


b=c
else:
a=c

return (a + b) / 2, iterations

# Newton-Raphson method (from earlier example)


def newton_raphson_nr(f, df, x0, tol=1e-6, max_iter=100):
x = x0
iterations = []

for i in range(max_iter):
fx = f(x)
dfx = df(x)

if abs(dfx) < 1e-10:


break

x_new = x - fx / dfx
[Link]((i, x, fx))

if abs(x_new - x) < tol:


return x_new, iterations

x = x_new

return x, iterations

# Graphical analysis
with open("equation_graph.txt", "w") as f:
[Link]("# x\tf(x)\n")
for x in [-3 + i/100 for i in range(700)]:
[Link](f"{x:.2f}\t{f(x):.6f}\n")

# Bisection
root_bis, _ = bisection(f, 2, 3)
print(f"Bisection root: {root_bis:.8f}")
# Newton-Raphson
root_nr, _ = newton_raphson_nr(f, df, 2.5)
print(f"Newton-Raphson root: {root_nr:.8f}")

# Verify
print(f"f({root_nr:.8f}) = {f(root_nr):.2e}")

GNUPlot Visualization:

set title "Finding Root of x³ - 2x - 5 = 0"


set xlabel "x"
set ylabel "f(x)"
set xrange [-3:4]
set yrange [-10:20]
set grid

f(x) = x**3 - 2*x - 5

plot f(x) with lines linewidth 2 title "f(x) = x³ - 2x - 5", \


0 with lines linewidth 1 title "y = 0"

set label "Root ≈ 2.095" at 2.1, 2

SECTION 7: IMPORTANT FUNCTIONS REFERENCE

Mathematical Functions (Python math module)


import math

# Trigonometric
[Link](x) # Sine (x in radians)
[Link](x) # Cosine
[Link](x) # Tangent
[Link](x) # Inverse sine
[Link](x) # Inverse cosine
[Link](x) # Inverse tangent
[Link](x) # Convert radians to degrees
[Link](x) # Convert degrees to radians

# Exponential and logarithmic


[Link](x) # e^x
[Link](x) # Natural logarithm (ln x)
math.log10(x) # Base 10 logarithm
[Link](x, base) # Logarithm with arbitrary base
[Link](x, y) # x^y (same as x**y)
[Link](x) # Square root

# Rounding and absolute value


[Link](x) # Smallest integer >= x
[Link](x) # Largest integer <= x
[Link](x) # Integer part
[Link](x) # Absolute value
abs(x) # Absolute value (built-in)

# Other useful functions


[Link](n) # n!
[Link](a, b) # Greatest common divisor
[Link](x) # Check if x is NaN
[Link](x) # Check if x is infinity

# Constants
[Link] # π ≈ 3.14159...
math.e # e ≈ 2.71828...
[Link] # 2π ≈ 6.28318...
String and List Operations

# String methods
[Link]() # Convert to uppercase
[Link]() # Convert to lowercase
[Link]() # Remove leading/trailing whitespace
[Link](old, new) # Replace substring
[Link](sep) # Split into list
[Link](list) # Join list into string
[Link](sub) # Find index of substring
[Link](prefix) # Check if starts with
[Link](suffix) # Check if ends with
[Link](*args, **kwargs) # Format string

# List methods
[Link](x) # Add element to end
[Link](iterable) # Add multiple elements
[Link](index, x) # Insert at position
[Link](x) # Remove first occurrence
[Link](index) # Remove and return element
[Link]() # Sort in-place
[Link]() # Reverse in-place
[Link](x) # Count occurrences
[Link](x) # Find index of element
[Link]() # Remove all elements

# Built-in functions
len(x) # Length
max(iterable) # Maximum
min(iterable) # Minimum
sum(iterable) # Sum
sorted(iterable) # Return sorted copy
enumerate(iterable) # (index, value) pairs
zip(*iterables) # Combine iterables
range(start, stop, step) # Generate sequence
FINAL TIPS FOR EXAM SUCCESS

Code Writing Tips

1. Always include comments explaining logic


2. Test your code with simple examples first
3. Check for edge cases (division by zero, empty lists, etc.)
4. Verify outputs match theoretical results
5. Use meaningful variable names

GNUPlot Tips

1. Always set labels and titles


2. Save plots to files (PNG/PDF for exam)
3. Use set grid for easier reading
4. Test plots interactively before saving
5. Document your scripts with comments

Practical Exam Strategy

1. Read questions carefully - understand what's asked


2. Plan your approach before coding
3. Write clean, organized code
4. Generate data files clearly
5. Create publication-quality graphs
6. Verify numerical results against theory
7. Be ready to explain your code in viva

Common Mistakes to Avoid

â​Œ Forgetting to import math module


â​Œ Using degrees instead of radians (or vice versa)
â​Œ Not checking convergence conditions
â​Œ Plots without labels/titles
â​Œ Not saving output files
â​Œ Off-by-one errors in loops
â​Œ Dividing by zero
â​Œ Not handling edge cases

Good Luck with Your Practical Exams!

This comprehensive guide covers all major topics from the WBSU/CU Physics
Honours GNUPlot and Python practical syllabus. Master these concepts,
practice the problems, and you'll excel in your exams!

You might also like