Module 1 PDF
Document Details
Uploaded by Deleted User
Tags
Related
Summary
This document provides an introduction to computational physics, introducing concepts like solving complex problems, simulating phenomena, and understanding fundamental physics. It also discusses fundamental concepts of computer science including programming languages and their categorization as compilers or interpreters. This document provides a high-level overview for learning computer science.
Full Transcript
Lecture:1 date: 05/09/2024 () Why computation ? Computational physics is a crucial field within the broader discipline of physics. It helps in: 1. Solving Complex Problems: Analytical solutions to physical problems are often difficult or as those involving many interacting p...
Lecture:1 date: 05/09/2024 () Why computation ? Computational physics is a crucial field within the broader discipline of physics. It helps in: 1. Solving Complex Problems: Analytical solutions to physical problems are often difficult or as those involving many interacting particles, nonlinear dynamics, or chaotic systems. Computational physics allows scientists to tackle these problems using numerical methods and algorithms. 2. Simulating Real-World Phenomena: useful in areas like climate modeling, astrophysics, material science, and quantum mechanics, where direct experimentation may be impractical, too expensive, or even impossible. 3. Predictive Power saves sweat, time and money: Computational models can predict the behavior of physical systems under different conditions. For example, estimate the performance of new materials before they are synthesized in the lab. 4. Understanding Fundamental Physics: Through simulations, computational physics helps uncover insights into fundamental processes by using thought experiments and numerical simulations. Fundamentals of Computations Computers generally operate in a 2-step cycle: 1. Fetch the Instruction The computer retrieves the instruction from memory. 2. Execute the Instruction The computer performs the operation specified by the instruction. These two steps are continuously repeated in a loop. Components of a Computer System Information Processing System CPU (Central Processing Unit): The brain of the computer, responsible for executing instructions. Memory: Stores data and instructions to be processed. Environment Input Devices: Devices like keyboards, mice, etc., that provide data to the computer. Output Devices: Devices like monitors and printers, which present the results of computations. Programs and Code Program: A sequence of instructions executed by the CPU. Code: The textual representation of these instructions. The CPU can only process instructions written in machine language. Machine Language (or machine code) consists of binary digits: 0 and 1. However, the code developed by humans is written in text form, not binary. To process these human-readable instructions (High level code), the text code must be converted into binary form(Low level code). This conversion can be done in two ways: 1. Compiling Converts the entire program into machine code at once before execution. 2. Interpreting Converts and executes code line by line in real time. Based on these methods programming languages can be categories in Compiler languages vs. Interpretation languages: Compiler Languages: In compiled languages, the source code is transformed into machine code (binary code) by a compiler before it can be executed. Source Code → Machine Code → Execution. Examples; C, C++, Fortran. Advantages: Compiled code generally runs faster because the CPU can execute without any additional processing. Optimization: Compilers can optimize the code during compilation, leading to more efficient executables. Disadvantages: Portability: Specific to the architecture it was compiled for, so it may not run on other types of systems without recompilation. Interpretation Languages: The source code is executed line-by-line by an interpreter. There is no separate compilation step that generates machine code. Source Code → Interpreter → Execution. Examples: Python, JavaScript, Ruby, PHP. Advantages: Portability: Interpreted languages are generally more portable because the source code can be executed on any system. Ease of Debugging: Since the code is executed line-by-line, it's easier to identify and fix errors as they occur during execution. Disadvantages: Performance: Interpreted code is generally slower than compiled code because the interpreter must process each statement at runtime. Use Cases: Compiler Languages are often used in systems programming, game development, Big Scientific Computings and applications where performance is critical. Interpreted Languages are commonly used for scripting, web development, and situations where ease of development and cross-platform compatibility are prioritized. Components of a Programming Language A programming language typically includes the following components: 1. Data Type Objects defined in the program have certain basic characteristics that describe their nature. Example: real , string or integer. 2. Data Structure Data can be organized and represented in complex forms. Example: Arrays , List. 3. Variables A storage location that holds data or values. 4. Assignments A statement that sets or re-sets the value stored in a variable. Example: a = 3 + 1 Lecture:2 -Python Basics Difference Between Real and Integer 1. Real Definition: A real number represents a value that can have a fractional pn)points. Operations: Supports arithmetic operations including addition, subtraction, multiplication, and division. Floating-point precision can affect the accuracy of results. **Ex ```python temperegrees Celsius hesents 175.4 cm 2. Integer Definition: An integer is a whole number that can be positive, negative, or zero, but does not include any fractional or decimal part. Data Type: In programming languages, integers are typically include decimal values. Operations: Supports arithmetic operations including addition, subtraction, multiplication, and integer division. Integers are exact, without floating-point rounding e- Example: age = 30 # Represents the age of a person count = 7 # Repressentation, whereas integers are exact. Usage: Use real numbers when precision with decimals is required (e.g., measurements), and use integers for counts, indexing, or whole number calculations. You can always change the data type by using: int() float() str() The three important structure of programing in Python: 1. if , elif , else These are used to execute different blocks of code based on certain conditions. if : Executes a block of code if the condition is true. elif : Checks another condition if the previous if condition is false. else : Executes a block of code if all preceding conditions ar else: print("x is less than 10") In : ## example x = 10 if x > 10: print("x is greater than 10") elif x == 10: print("x is equal to 10") else: print("x is less than 10") x is equal to 10 2. The for Loop The for loop is used to iterate over a sequence (such as a list, array, or range) and execute a block of code for each item in the sequence. pytprint(fruit) print(fruit) In : # Iterating over a range for i in range(0,5): # Python will start indexing from 0 and will stop before 5 print(i) # Iterating over a list fruits = ["apple", "banana", "cherry"] for c in fruits: print(c) 0 1 2 3 4 apple banana cherry 3. Use of Functions Functions are reusable blocks of code designed to perform a specific task. They help in organizing code, avoiding repetition. You need to call the function when you need In : ## Defining function: def square(number): sqr= number ** 2 return sqr ## Using it for calculations print(square(4)) 16 In : ## Summing two square print(square(4)+square(3)) 25 Assignment: 1 1. Write a code for calculating factorial of a integer: 1. Without using Function structure 2. With defining a Function 2. Write a code to check if 3 numbers can make sides of a right angled triangle. 3. Write a code to calculate Combinations (nCr). ** Help: To get a single input from the user: ** number = input("Enter a number: ") References: GeeksforGeeks Python Programming Language Tutorial W3Schools Python Tutorial Lecture :3 (Data Visualization) Classical Types of Plots and Their Uses Before plotting any data, you must ask two key questions: 1. What data type do I have? Qualitative (Categorical): Data that represents categories or groups. Examples include gender, regions, product categories. Quantitative (Numerical): Data that represents measurable quantities. Examples include age, income, height. 2. What important observations or results do I want to show? Relationships: How two or more variables are related. Example: Scatter plot showing correlation between height and weight. Trends: How a variable changes over time. Example: Line plot showing temperature change throughout a day. Ranking: Comparing multiple categories to show their order. Example: Bar plot showing product sales. Evolution: Changes in data points over a period of time. Example: Area plot to show cumulative growth. Clustering: Grouping data into distinct clusters. Example: Scatter plot with colored clusters to show distinct groups in a dataset. Contribution or Proportion: Showing how much each category contributes to the whole. Example: Pie chart showing market share. Distribution: Displaying how data points are spread across different ranges or values. Example: Histogram showing the distribution of test scores. Choosing the Right Plot: Qualitative Data: Bar plots, Pie charts. Quantitative Data: Line plots, Histograms, Scatter plots. For Relationships: Scatter plots, Heatmaps. For Trends: Line plots, Area plots. For Proportion: Pie charts, Stacked bar plots. For Distribution: Histograms, Box plots. 1. Line Plot Use: Shows trends or changes over time. Useful for tracking data points in a continuous dataset (e.g., time series). Example: Stock prices over time, temperature changes throughout a day. Library: plt.plot(x, y) in matplotlib. 2. Bar Plot Use: Compares quantities across categories. Great for showing the relationship between different groups. Example: Sales numbers of different products, comparison of states with the most sales. Library: plt.bar(categories, values) in matplotlib. 3. Horizontal Bar Plot Use: A horizontal bar plot is used when you want to compare quantities across categories, similar to a regular bar plot but with horizontal bars instead of vertical. This is particularly useful when you have long category names or when you're comparing a large number of categories. Example: Comparing sales numbers of different products where the product names are long or there are many categories. Library: plt.barh(categories, values) in matplotlib. 4. Grouped Bar Plot Use: Compares multiple categories side by side within each group. Shows two or more categories at the same time. Example: Comparison of male vs. female participation in different sports. Library: plt.bar() with shifted x coordinates in matplotlib. 5. Histogram Use: Displays the distribution of a continuous variable. Shows the frequency of data points within specific intervals (bins). Example: Distribution of test scores, height distribution in a population. Library: plt.hist() in matplotlib. 6. Pie Plot Use: Shows the proportion of each category as a slice of a pie. Useful for displaying the relative sizes of parts to a whole. Example: Market share of different companies, budget allocation by category. Library: plt.pie(sizes, labels=labels) in matplotlib. 7. Scatter Plot Use: Displays the relationship between two continuous variables. Useful for identifying correlations or patterns. Example: Relationship between hours studied and exam scores, height vs. weight. Library: plt.scatter(x, y) in matplotlib. 8. Contour Plot Use: Displays the levels of a function of two variables. Useful for visualizing topographical data or surface plots. Example: Elevation levels on a map, density estimation. Library: plt.contour(X, Y, Z) in matplotlib. 9. 3D Plot Use: Visualizes data with three dimensions. Useful for representing complex datasets and surfaces. Example: 3D surface plots. Library: 3D Surface Plot: ax.plot_surface(X, Y, Z) with mpl_toolkits.mplot3d in matplotlib. Templates for all these 2D plots have been provided below. Try to explore it as much as you can. The most important ones are line plot, bar plot, histogram, pie plot, scatter plot, contour plot. Few lines aboiut the normal distribution: Normal Distribution The normal distribution, or Gaussian distribution, is a continuous distribution that is symmetrical around its mean. It has a characteristic bell-shaped curve where most of the data points are concentrated around the mean, and the decreases as you move away The distribution is defined by two parameters: the mean (μ) and the standard deviation (σ). A large part of statistics and data analysis relies on the properties of the normal distribution, as it models many natural phenomena and measurement errors. Reference Plots: Line plot(simple One) In : import matplotlib.pyplot as plt x = [1,2,3,4] y = [1,2,3,4] plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3, marker='o', markerfacecolor='blue', markersize=12) plt.xlabel('x – axis') plt.ylabel('y – axis') plt.title('My first graph') plt.show() Line plot(with allmost all parameters) In : import matplotlib.pyplot as plt import numpy as np # Generate some example data x = np.linspace(0, 10, 100) y_sin = np.sin(x) y_cos = np.cos(x) # Create the plot plt.figure(figsize=(8, 6)) # Plot the sine wave with a specific style plt.plot(x, y_sin, color='blue', linestyle='--', linewidth=2, marker='o', marker markerfacecolor='red', markeredgewidth=1, label='Sine Wave') plt.plot(x, y_cos, color='green', linestyle='-', linewidth=2, marker='x', marker markerfacecolor='yellow', markeredgewidth=1, label='Cosine Wave') # Add labels to the axes plt.xlabel('X-Axis Label', fontsize=12) plt.ylabel('Y-Axis Label', fontsize=12) # Add a title to the graph plt.title('Sine and Cosine Plot Example', fontsize=14) # Add a grid with both major and minor ticks plt.grid(True, which='both') # Set axis limits plt.xlim(0, 10) plt.ylim(-1.5, 1.5) # Customize major and minor ticks plt.xticks(fontsize=10) plt.yticks(fontsize=10) plt.minorticks_on() # Set the number of minor ticks for x and y axes plt.gca().xaxis.set_minor_locator(plt.MultipleLocator(0.5)) plt.gca().yaxis.set_minor_locator(plt.MultipleLocator(0.25)) # Customize minor ticks appearance plt.tick_params(which='minor', length=4, color='gray') # Add a legend plt.legend(loc='upper right', fontsize=12) # Show the plot plt.show() Histogram(One plot) In : import matplotlib.pyplot as plt import numpy as np mu, sigma = 170, 10 # Average height of 170 cm, standard deviation of 10 cm # Generate random heights for 500 students heights = np.random.normal(mu, sigma, 500) plt.figure(figsize=(9, 6)) plt.hist(heights, bins=40, density=False, alpha=0.8, color='green', edgecolor='b plt.xlabel('Height (cm)', fontsize=12) plt.ylabel('Frequency', fontsize=12) plt.legend(loc='upper right', fontsize=12) plt.title('Distribution of Student Heights', fontsize=14) # Show the plot plt.show() Histogram(Two plot) In : import numpy as np import matplotlib.pyplot as plt mu1, sigma1 = 170, 10 # Average height of 170 cm, standard deviation of 10 cm mu2, sigma2 = 150, 10 # Average height of 170 cm, standard deviation of 10 cm # Generate data: heights_male = np.random.normal(mu1, sigma1, 500) heights_female = np.random.normal(mu2, sigma2, 500) # Plot the histogram plt.figure(figsize=(9, 6)) plt.hist(heights_male, bins=20, density=False, alpha=0.8, color='blue', edgecolo plt.hist(heights_female, bins=20, density=False, alpha=0.5, color='red', edgecol # alpha parameter is for transparency (or opacity) of the plot elements. # Add title, labels and legend plt.title('Distribution of Student Heights', fontsize=14) plt.xlabel('X-Axis Label', fontsize=12) plt.ylabel('Y-Axis Label', fontsize=12) plt.legend(loc='upper right', fontsize=12) # Show the plot plt.show() Template for Bar plot: In : import numpy as np import matplotlib.pyplot as plt # Generating data categories = ['Group 1', 'Group 2', 'Group 3', 'Group 4'] female_values = [10, 15, 9, 14] male_values = [12, 14, 8, 10] # Set the width of the bars or you can choose bin number bar_width = 0.35 # Set the positions of the bars on the x-axis x = np.arange(len(categories)) # create the bar plot for male and female values plt.figure(figsize=(9, 6)) plt.bar(x, male_values, width=bar_width, label='Male', color='blue') plt.bar(x + bar_width, female_values, width=bar_width, label='Female', color='gr # Add labels and title plt.xlabel('Categories') plt.ylabel('Values') plt.title('Grouped Bar Plot Example (Male vs Female)') # Add category labels to the x-axis plt.xticks(x + bar_width / 2, categories) # Add a legend plt.legend() # Show the plot plt.show() Template for horizontal Bar plot: In : # Generating data categories = ['Group 1', 'Group 2', 'Group 3', 'Group 4'] female_values = [10, 15, 9, 14] male_values = [12, 14, 8, 10] # Set the width of the bars bar_width = 0.35 y = np.arange(len(categories)) # Create the bar plot for male and female values plt.figure(figsize=(9, 6)) plt.barh(y, male_values, height=bar_width, label='Male', color='blue') plt.barh(y + bar_width, female_values, height=bar_width, label='Female', color=' plt.ylabel('Categories') plt.xlabel('Values') plt.title('Grouped Bar Plot Example (Male vs Female)') # Add category labels to the y-axis plt.yticks(y + bar_width / 2, categories) plt.legend() plt.show() Scatter plot: In : x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y = [12, 4, 5, 7, 6, 8, 9, 11, 12, 12] plt.scatter(x, y) plt.xlabel('x – axis') plt.ylabel('y – axis') plt.title('Scatter Plot') plt.xticks(np.arange(min(x), max(x)+1, 1.0)) # +1 to include the maximum value plt.show() Contour Plot: In : feature_x = np.linspace(-3.0, 3.0, 30) feature_y = np.linspace(-3.0, 3.0, 30) [X, Y] = np.meshgrid(feature_x, feature_y) Z = X ** 2 + Y ** 2 plt.contourf(X, Y, Z) plt.colorbar() # Optional: adds a color bar to the plot plt.title('Contour Plot') plt.xlabel('X axis') plt.ylabel('Y axis') plt.show() 3D plots: In : from mpl_toolkits import mplot3d fig = plt.figure() ax = plt.axes(projection='3d') # Define data x = np.linspace(-5, 5, 100) y = np.linspace(-5, 5, 100) X, Y = np.meshgrid(x, y) Z = np.sqrt(X**2 + Y**2) # Create 3D surface plot ax.plot_surface(X, Y, Z, cmap='viridis') ax.set_title('3D Surface Plot') ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_zlabel('Z axis') plt.show() Reference: THough you don't need but if you are interested you can see this nice link. Data to Viz In [ ]: #factorial num= int(input("give me a number")) if num < 0: print('factorial for negative number is not defined') else: factorial=1 for i in range(1,num+1): factorial *= i print(f"factorial of {num}=={factorial}") In [ ]: # factorial as fuction def fact(num): if num < 0: return 'factorial for negative number is not defined' else: factorial=1 for i in range(1,num+1): factorial *= i return factorial In [ ]: num1, num2, num3= input("give me 3 numbers").split() num1, num2, num3 = float(num1), float(num2), float(num3) print(num1, num2, num3) list_num=[num1,num2,num3] list_num.sort() if list_num*list_num==list_num*list_num+list_num*list_num: print(f" Numbers form side of Right angled triangle") else: print(f" Numbers do not form side of Right angled triangle") Practical-1: Compute the area of a Circle and compare it with Analytic value: What do you understand by convergence of Solution. Trade off between accuracy and computational resources. In [ ]: import random import math import matplotlib.pyplot as plt import time import numpy as np def circle_area_montecarlo(radius, num_points, plot_points=False): points_inside = 0 points_outside = 0 inside_x = [] inside_y = [] outside_x = [] outside_y = [] for _ in range(num_points): # Generate random points within the square [-radius, radius] x [-radius, x = random.uniform(-radius, radius) y = random.uniform(-radius, radius) # print(x,y) if x**2 + y**2