Computational Physics

Similar documents
Computational Physics

Dr Richard Greenaway

Introduction to MATLAB

Introduction to MATLAB

Built-in Types of Data

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Lecture 2 FORTRAN Basics. Lubna Ahmed

PRECALCULUS MATH Trigonometry 9-12

MATHEMATICS FOR ENGINEERING TRIGONOMETRY

Introduction to Programming

Arithmetic and Logic Blocks

Macro Programming Reference Guide. Copyright 2005 Scott Martinez

MATLAB Workshop Dr. M. T. Mustafa Department of Mathematical Sciences. Introductory remarks

Starting MATLAB To logon onto a Temple workstation at the Tech Center, follow the directions below.

Basic stuff -- assignments, arithmetic and functions

Introduction to FORTRAN

5-2 Verifying Trigonometric Identities

Excel Tool: Calculations with Data Sets

Introduction to Scientific and Engineering Computing, BIL108E. Karaman

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

FORTRAN Basis. PROGRAM LAYOUT PROGRAM program name IMPLICIT NONE [declaration statements] [executable statements] END PROGRAM [program name]

Introduction to Engineering gii

3+2 3*2 3/2 3^2 3**2 In matlab, use ^ or ** for exponentiation. In fortran, use only ** not ^ VARIABLES LECTURE 1: ARITHMETIC AND FUNCTIONS

Single row numeric functions

Ebooks Chemical Engineering

Macro B Reference Guide

SCIENTIFIC CALCULATOR OPERATION GUIDE < EL-531TG/531TH/531TS >

Excel R Tips. is used for multiplication. + is used for addition. is used for subtraction. / is used for division

Trigonometric Functions of Any Angle

The Graphing Calculator

1001ICT Introduction To Programming Lecture Notes

GRAPH 4.4. Megha K. Raman APRIL 22, 2015

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

5-2 Verifying Trigonometric Identities

MATLAB Constants, Variables & Expression. 9/12/2015 By: Nafees Ahmed

# Import constants pi2, pip2, pip4 (2*pi, pi/2, pi/4). use Math::Trig ':pi';

Functions and Inverses ID1050 Quantitative & Qualitative Reasoning

Statistical Data Analysis: Python Tutorial

Data Types and Basic Calculation

Introduction to GNU-Octave

ELEMENTARY MATLAB PROGRAMMING

MATH EXAM 1 - SPRING 2018 SOLUTION

Pre Calculus Worksheet: Fundamental Identities Day 1

LAB 1 General MATLAB Information 1

Numerical Modelling in Fortran: day 2. Paul Tackley, 2017

AMS 27L LAB #1 Winter 2009

Downloaded from Chapter 2. Functions

Math 2250 MATLAB TUTORIAL Fall 2005

Parametric Representation throughout Pre-Calculus Richard Parr Rice University School Mathematics Project

Maths Functions User Manual

: Find the values of the six trigonometric functions for θ. Special Right Triangles:

Consider this m file that creates a file that you can load data into called rain.txt

JUN / 04 VERSION 7.0

Lab 1 Intro to MATLAB and FreeMat

MYSQL NUMERIC FUNCTIONS

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

Section 7.1. Standard position- the vertex of the ray is at the origin and the initial side lies along the positive x-axis.

Welcome. Please Sign-In

PIV Programming. Today s Contents: 1. Matlab Programming 2. An example of PIV in Matlab code 3. EDPIV 4. PIV plugin for ImageJ 5.

Unit 2: Trigonometry. This lesson is not covered in your workbook. It is a review of trigonometry topics from previous courses.

ENGI Introduction to Computer Programming M A Y 2 8, R E Z A S H A H I D I

Polar Coordinates. 2, π and ( )

8-1 Simple Trigonometric Equations. Objective: To solve simple Trigonometric Equations and apply them

EXCEL HINTS. Navigation Nomenclature (for this class)

Computer Science 121. Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans

Function f. Function f -1

TS Calc 1.6 User Guide

hp calculators HP 50g Hyperbolic functions The MTH (MATH) menu Hyperbolic trigonometric functions Practice using hyperbolic trigonometric functions

Computer Programming in MATLAB

The Very Basics of the R Interpreter

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

Script started on Thu 25 Aug :00:40 PM CDT

Functions and Transformations

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

A. Matrix-wise and element-wise operations

College Technical Math 2

Graphing Calculator Scientific Calculator Version 2.0

SCAD Soft. Slope. User manual. Stability analysis of slopes. Version 1.5

Common Core Standards Addressed in this Resource

Basic types and definitions. Chapter 3 of Thompson

A Guide to Using Some Basic MATLAB Functions

What is log a a equal to?

A General Introduction to Matlab

Our Strategy for Learning Fortran 90

# Import constants pi2, pip2, pip4 (2*pi, pi/2, pi/4). use Math::Trig ':pi';

Algebra II. Slide 1 / 162. Slide 2 / 162. Slide 3 / 162. Trigonometric Functions. Trig Functions

Math Machines: Designing Motions and More MM:DMM Readme (2016)

Introduction to Programming with RAPTOR

Julia Calculator ( Introduction)

Arithmetic. 2.2.l Basic Arithmetic Operations. 2.2 Arithmetic 37

Physics 251 Laboratory Introduction to Spreadsheets

Math for Geometric Optics

How to Design Programs Languages

GREENWOOD PUBLIC SCHOOL DISTRICT Algebra III Pacing Guide FIRST NINE WEEKS

A lg e b ra II. Trig o n o m e tric F u n c tio

To graph the point (r, θ), simply go out r units along the initial ray, then rotate through the angle θ. The point (1, 5π 6

Python. Olmo Zavala R. Python Exercises. Center of Atmospheric Sciences, UNAM. August 24, 2016

Ganado Unified School District Pre-Calculus 11 th /12 th Grade

Transcription:

Computational Physics Python Programming Basics Prof. Paul Eugenio Department of Physics Florida State University Jan 17, 2019 http://hadron.physics.fsu.edu/~eugenio/comphy/

Announcements Exercise 0 due end of day Friday

Arithmetic in Python In most places where you can use a single variable in Python you can also use a mathematical expression print(height + offset) Basic mathematical operations x + y # addition x - y # subtraction x * y # multiplication x / y # division x**y # raising x to the power y x // y # integer division: example 5//3 returns 1 x % y # integer modulo remainder: example 5%3 returns 2 requires from future import division

Easy Readable Expressions Several mathematical operations can be combined together to make a more complicated expression along with the use of parentheses () to dictate the order of mathematical operations length = (x-x0)*(x-x0) + (y-y0)**2 + (z-z0)**2 Add spaces between the parts of a mathematical expression to make it easier to read. When different priorities are used, add a space around the operators with the lowest priority(ies). Never use more than one space, and always have the same amount of whitespace on both sides of a binary operator. YES: i = i + 1 i += 1 x = x*2 1 hypo2 = x*x + y*y c = (a+b) * (a-b) xsquared = x**2 NO: i=i+1 i +=1 x = x * 2 1 hypo2 = x * x+y * y c = (a +b) * (a- b) xsquared=x ** 2

Arithmetic Tricks and Short Cuts x += 1 # add 1 to x, same as x = x + 1 x -= 4 # subtract 4 from x, same as x = x - 4 x *= -2.6 x /= 5*y # x = x * -2.6 # x = x / (5*y) x //= 3.4 # x = int(x / 3.4) Multiple Assignments in a Single Statement x, y = 1, 2.5 x, y = 2*x*y+1, (x+y)/3 NICE! It is important to note that the whole right-hand side of the equation is calculated by the computer before assigning the left-hand values

Example: Multiple Assignments Sequential Assignments x = 1 # value: x = 1 y = 1 # values: X = 1 & y = 1 x = 2*y + 1 # values: x = 3 & y = 1 y = 2*x + 1 # values: x = 3 & y = 7 Simultaneous Assignments x, y = 1, 1 # values: x = 1 & y = 1 x,y = 2*y + 1, 2*x +1 # values: x = 3 & y = 3 Be Careful What You Want May Not Be What You Get

Functions, Packages, and Modules Python comes with facilities for performing many operations, from basic arithmetic to complex calculations, visualizations, and operations. These facilities are included in modules and packages(a collection of modules). In order to use these facilities, one must import the function or module into the program. Standard Mathematical Functions are provided in the math module. log() # natural logarithm log10() # log base 10 exp () # exponential sin(), cos(), tan() # trig functions(radians) asin(), acos(), atan() # inverse trig funct. sinh(), cosh(), tanh() # hyperbolic trig funct. sqrt() # positive square root plus values for π and e and many more functions

math Mathematical functions Using interactive python for help hpc-login 434% python Python 2.7.5 Type "help", "copyright", "credits" or "license" for more information. >>> help("math") Help on module math: NAME math FILE /opt/python27/anaconda/lib/python2.7/lib-dynload/math.so MODULE DOCS http://docs.python.org/library/math DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. acosh(...) Return the hyperbolic arc cosine (measured in radians) of x. asin(...) asin(x) Return the arc sine (measured in radians) of x.

Importing Math Functions Importing a Module import math math.sin(1.57) # returns 0.9999996.. math.sin(math.pi/2) # returns 1.0 math.sin(math.degrees(45)) # returns 0.707107.. math.degrees(math.asin(1/math.sqrt(2))) # equals 45 Importing Functions from a Module from math import sin, asin, pi, degrees, sqrt sin(1.57) # returns 0.9999996.. sin(pi/2) # returns 1.0 sin(degrees(45)) # returns 0.707107.. degrees(asin(1/sqrt(2))) # equals 45 avoid using: from math import * (import all functions) as it can cause unknown behavior

Avoid import * Import All Functions From a Module from math import * # a quick and dirty way to import sin(1.57) sin(pi/2) Importing Functions over Functions from math import * from numpy import * # NumPy is the fundamental package for # scientific computing with Python. sin(1.57) # which sin()? sin(pi/2) # math or numpy? It's Better to Import Modules and Scope Functions import math as m import numpy as np m.sin(1.57) np.sin(1.57) np.sin([np.pi,np.pi/2]) # returns: array([ 1.22464680e-16, 1.00e+00])

A ball dropped from a tower A ball is dropped from a tower of height h with initial velocity zero. Write a program that asks the user to enter the height of the tower in meters and then calculates and prints the time the ball takes until it hits the ground, ignoring air resistance. Use your program to calculate the time for a ball dropped from a 100 m high tower.

A ball dropped from a tower #! /usr/bin/env python #! /usr/bin/env python # ball_drop.py is program which calculates the time for a # # ball ball_drop.py to drop from is program a height which to the calculates ground. the It asks time the for a # # user ball to to enter drop from a value a height for height to the (in ground. meters) It and asks prints the # # the user results to enter to a the value screen. for height (in meters) and prints # # the results to the screen. # # Paul Eugenio # # PHZ4151C Paul Eugenio # # Jan PHZ4151C 17, 2019 # Jan 17, 2019 # program header code from # program future header import code division, print_function import from future math as m import division, print_function import math as m # # # main body of program # # main body of program g # = 9.81 # acceleration due to gravity at the Earth's surface (m/s**2) g = 9.81 # acceleration due to gravity at the Earth's surface (m/s**2) height = float(raw_input( Enter the height of the tower (in meters): )) height = float(raw_input( Enter the height of the tower (in meters): )) # distance = a*t**2/2 time # distance = m.sqrt(2*height/g) = a*t**2/2 time = m.sqrt(2*height/g) print( The ball takes, time, seconds to hit the ground from a height of, print( The height, meters. ball takes, ) time, seconds to hit the ground from a height of, height, meters. )

A ball dropped from a tower A ball is dropped from a tower of height h with initial velocity zero. Write a program that asks the user to enter the height of the tower in meters and then calculates and prints the time the ball takes until it hits the ground, ignoring air resistance. Use your program to calculate the time for a ball dropped from 100 m high tower. hpc-login 480% nedit ball_drop.py & hpc-login 480% chmod +x ball_drop.py hpc-login 481% ball_drop.py ( or./ball_drop.py ) Enter the height of the tower (in meters): 100 The ball takes 4.515 seconds to hit the ground from a height of 100.0 meters. hpc-login 482%

Polar to Cartesian Coordinates Write a program to perform the inverse operation to that of Example 2.2. That is, ask the user for the Cartesian coordinates x, y of a point in two-dimensional space, and calculate and print the corresponding polar coordinates, with the angle θ given in degrees. r = sqrt(x*x + y*y) θ = atan(y/x) x = r cos(θ) y = r sin(θ) θ The atan() math function is limited to +90 o to -90 o see python: help( math ) atan2(...) atan2(y, x) Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered.

Polar to Cartesian Coordinates #! /usr/bin/env python #! /usr/bin/env python # cartesian2polar.py is program which calculates the 2D radius and # # polar cartesian2polar.py angle given the is cartesian program which coordinates. calculates The the results 2D radius are and printed # # to polar the angle screen. given the cartesian coordinates. The results are printed # # to the screen. # # Paul Eugenio # # PHZ4151C Paul Eugenio # # Jan PHZ4151C 17, 2019 # Jan 17, 2019 # program header code from # program future header import code division, print_function import from future math as m import division, print_function import math as m # main body of program # main body of program # get input values x # = get float(raw_input("enter input values the x coordinate: ")) y x = = float(raw_input("enter float(raw_input("enter the the y x coordinate: coordinate: ")) ")) y = float(raw_input("enter the y coordinate: ")) # transform values from cartesian to polar r # = transform m.sqrt(x*x values + y*y) from cartesian to polar phi r = = m.sqrt(x*x m.atan2(y, + x) y*y) phi = m.atan2(y, x) print("the polar radius is", r, ", and the polar angle is", print("the m.degrees(phi), polar radius "degrees.") is", r, ", and the polar angle is", m.degrees(phi), "degrees.")

Polar to Cartesian Coordinates Write a program to perform the inverse operation to that of Example 2.2. That is, ask the user for the Cartesian coordinates x, y of a point in two-dimensional space, and calculate and print the corresponding polar coordinates, with the angle θ given in degrees. hpc-login 480% nedit cartesian2polar.py & hpc-login 480% chmod +x cartesian2polar.py hpc-login 481% cartesian2polar.py Enter the x coordinate: 2 Enter the y coordinate: 2 The polar radius is 2.82842712475 and the polar angle is 45.0 degrees. hpc-login 482%

This Week s Exercise Python Basics Exercise set #1 DUE DATE: January 25

Let's get working