Unit 2: Computer Programming (Lab: PHYDSC354P)

Table of Contents

1. Laboratory Objectives

The objective of this unit is to utilize C or Python to solve complex physical problems that cannot be easily addressed analytically. You will focus on algorithm development, numerical stability, and the visualization of experimental data.

2. Python for Physics: Core Concepts

Python is widely used in physics due to its readability and powerful libraries like NumPy (for numerical arrays) and SciPy (for scientific constants and functions).

Key Advantage: In Python, you don't need to worry about memory management or low-level variable declarations, allowing you to focus on the Physics Logic.

3. Finding Roots of Equations

In many physics problems, we need to find the value of x where f(x) = 0.

Newton-Raphson Method

An iterative method that uses the derivative of a function to find its roots quickly.

def newton_raphson(f, df, x0, tol): while abs(f(x0)) > tol: x0 = x0 - f(x0)/df(x0) return x0

4. Numerical Integration

This is essential when the integral of a function has no closed-form solution.

5. Matrix Operations and Linear Equations

Physics systems often lead to simultaneous linear equations. You will use Gauss-Elimination or LU Decomposition to solve these. In Python, NumPy provides the numpy.linalg module for this.

import numpy as np A = np.array([[3, 1], [1, 2]]) B = np.array([9, 8]) X = np.linalg.solve(A, B) # Solves AX = B

6. Data Visualization with Matplotlib

A critical part of any physics lab is plotting results. You will learn to create high-quality graphs with labels, legends, and grid lines.

import matplotlib.pyplot as plt plt.plot(time, velocity) plt.xlabel('Time (s)') plt.ylabel('Velocity (m/s)') plt.title('Projectile Motion') plt.show()

Lab Exam Focus Corner

Frequently Asked Questions

Common Mistakes

Practical Tips

Tip: When writing a C program for numerical methods, always use the double data type instead of float to ensure sufficient precision for physics calculations.