├── 3D_point_classes.py ├── Basic_vector_manipulation.py ├── Earth_moon_lagrange_point.py ├── Non_linear_equations.py ├── README.md ├── RK4_advancement.py ├── ball_euler_integration.py ├── binomial_dist.py ├── cartesian_coords.py ├── data_histogram.py ├── erfc_gaussian_prob.py ├── euler_advancement.py ├── factorial_matlab.py ├── factorials.py ├── falling_Ball.py ├── float_comparison.py ├── interpolation.py ├── large_data_sets.py ├── leapfrog_method.py ├── lin_alg_solve.py ├── method_of_least_squares.py ├── newton.py ├── plotting_function.py ├── prime_numbers.py ├── reflection.py ├── riemann_sums.py ├── rydberg.py ├── time_counter.py ├── transformation_points.py └── vector_norm.py /3D_point_classes.py: -------------------------------------------------------------------------------- 1 | # 3D classes points 2 | 3 | class Point3D(object): 4 | def __init__(self, x,y,z): 5 | self.x = x 6 | self.y = y 7 | self.z = z 8 | 9 | def __repr__(self): 10 | return "(%d,%d,%d)" % (self.x, self.y, self.z) 11 | 12 | #tester 13 | my_point = Point3D(1,2,3) 14 | print my_point 15 | -------------------------------------------------------------------------------- /Basic_vector_manipulation.py: -------------------------------------------------------------------------------- 1 | # lists 2 | [0, 4, 5] 3 | [0, 0.1, 1+3j] 4 | 5 | x = 1 6 | y = 2 7 | r = [x,y] 8 | print r 9 | # if x or y changes later on, the list doesn't change 10 | 11 | r[0] = 2 12 | 13 | #expressions for x, y coordinates 14 | x = 1 15 | y = 2 16 | r = [ x*2 , y+1/sqrt(y) ] 17 | 18 | # find the magnitude of vector a: 19 | a = [1.0, 3.0, 5.6] 20 | magnitude = sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]) 21 | 22 | sum[1,2,3] # returns the sum of the elements in common type --> 6 23 | 24 | max[1,2,3] #returns max value --> 3 25 | 26 | min[1,2,3] #returns min value --> 1 27 | 28 | len[1,2,3] # returns the length or number of elements --> 3 29 | 30 | #map : apply an operatino to ALL the elements of a list : NOTE in python 2, returns a list, but in python 3, returns an "iterator" where you need to convert to a list 31 | 32 | logr = map(log,r) #python 2 33 | 34 | map(lambda x: x+1, [1,2,3]) # --> [2,3,4] 35 | 36 | logr = list(map(log,r)) # python 3 37 | 38 | 39 | # append something to our list r 40 | r = [1.0, 1.5, 2.1, 3.6] 41 | r.append(5.6) 42 | print r 43 | 44 | # append --> create a list from scratch 45 | 46 | # remove an element "pop" 47 | r = [1.0, 1.5, 2.1, 3.6] 48 | r.pop() # note r.pop(n) removes n element, but SLOW 49 | print r 50 | 51 | 52 | ''' 53 | 54 | 2) arrays (different than lists!!) 55 | 56 | ** Used for vectors, matrices, images, etc ** 57 | 58 | - number of elements is FIXED 59 | - all elements must be the same type 60 | - arrays can be 2D, 3D, or higher 61 | - can do arithmetic on WHOLE arrays at once 62 | - array operatinos are faster 63 | - printout of arrays is different 64 | 65 | - creating arrays 66 | - numpy functions 67 | - ones, empty 68 | - convert list to array 69 | 70 | - reading arrays from a single/multiple column file 71 | 72 | - array operations 73 | - dot product 74 | - max, min, len 75 | - size, shape 76 | 77 | 78 | ''' 79 | # zeros array [0,0,0,0] fixedsize 80 | from numpy import zeros, ones, empty # note differences in array formations 81 | a = zeros(4, float) 82 | print a 83 | 84 | #convert list to array 85 | r = [1.0, 2.0, 4.0] 86 | a = array(r, float) # array name and type 87 | 88 | # multi-dimensional array 89 | from numpy import array 90 | a = array([ [1,2,3] , [4,5,6] ], int) 91 | print a 92 | 93 | 94 | # mutli-dimensional array - elements indexed in order row, then column 95 | a = zeros([2,2], int) #prints out [[0 0][0 0]] 96 | a [0,1] = 1 97 | a [1,0] = -1 98 | print (a) # prints out [[ 0 1][-1 0]] 99 | 100 | # note need to account for fact that indexed starts at 0 101 | 102 | 103 | # read arrays from a single/mulitple column file 104 | 105 | a = loadtxt("values.txt",float) 106 | 107 | # perform operations on the whole array at once 108 | a = array( [1.0,2.0,3.0] , float) 109 | b = array([4.0,5.0,6.0], float) 110 | 111 | c = a + b 112 | print c 113 | 114 | # Dot product ( to multiply the individual elements) 115 | from numpy import array, dot 116 | a = array( [1.0,2.0,3.0] , float) 117 | b = array([4.0,5.0,6.0], float) 118 | 119 | c = dot(a,b) 120 | print c #32 121 | 122 | 123 | # Check the size and shape of an array ( instead of max, min, len) 124 | a = array([[1.0, 2.0, 3.0], [4.0,5.0,6.0]], float) 125 | print a.size # --> 6 126 | print a.shape # --> (2,3) prints out row-column 127 | -------------------------------------------------------------------------------- /Earth_moon_lagrange_point.py: -------------------------------------------------------------------------------- 1 | # Finding the Earth - Moon Lagrange Point 2 | from numpy import arange, zeros, ones 3 | from pylab import plot, show, ylim 4 | 5 | G = 6.674e-11 6 | Me = 5.974e24 # mass earth 7 | Mm = 7.348e22 # math moon 8 | 9 | R = 3.844e8 #earth moon distance 10 | w= 2.662e-6 11 | 12 | k = w/G/Me 13 | rs = arange(1e6, 5e8,1.01e5) 14 | f = zeros(len(rs)) 15 | 16 | 17 | # set up Horizonatal and Vertical axis 18 | 19 | f0 = zeros(len(rs)) # array of zeros .. H line... becomes the x-axis ,, ( better way call line function) 20 | f1 = ones(len(rs)) 21 | f1 = f1*3.844e8 #vertical axis.... some special values 22 | 23 | for i in range(len(rs)): 24 | r = rs[i] 25 | f[i] = G*Me/r/r - G*Mm/(R-r)/(R-r) - w*w*r 26 | 27 | #plot (x,y)... plot cycles through colours 28 | plot(rs,f) 29 | plot(rs,f0) 30 | plot(f1,f) 31 | 32 | ylim(-0.1, 0.1) 33 | show() 34 | -------------------------------------------------------------------------------- /Non_linear_equations.py: -------------------------------------------------------------------------------- 1 | from numpy import exp 2 | from numpy import arange, zeros 3 | from pylab import show, plot 4 | # from 17.3.1 newman ex 6.13 5 | 6 | 7 | #binary search method: example 8 | x = arange(0.01,10.0,1.0) 9 | g = zeros(len(x),float) 10 | 11 | def g_x(x): 12 | return 5.0*exp( -x ) + x - 5.0 13 | 14 | #accuracy, displays up to 12 digits 15 | accuracy = 1e-12 16 | 17 | #interval left hand and right hand ( binary tree) 18 | ll = 4.01 #lower bound 19 | ul = 10.0 # upperbound 20 | 21 | 22 | 23 | # get middle of every tree, evaluate at that middle point, then check the sign 24 | 25 | 26 | g1 = g_x(ll) 27 | g2 = g_x(ul) 28 | 29 | if (g1*g2) > 0: 30 | print "sorry this is not in teh interval you are looking for" 31 | 32 | else: 33 | while( ul-ll ) > accuracy: 34 | 35 | #if interval is small enough stop 36 | # subdivide 37 | 38 | #divides into four - new upper upper, upper lower, upper lowe,r and lower lower, and midpoint 39 | 40 | ll1 = ll 41 | ul1 = (ll+ ul)/2.0 #midpoint of previous interval 42 | 43 | ll2 = ul1 44 | ul2 = ul 45 | 46 | print "midpoint", ul1 47 | 48 | 49 | #check for sign changes 50 | if (g_x(ll1)*g_x(ul1)) < 0: 51 | #this is the correct interval 52 | ll = ll1 53 | ul = ul1 54 | else: 55 | ll = ll2 56 | ul = ul2 57 | 58 | 59 | print "answer is:", (ll + ul)/2.0 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Computational_physics 2 | 3 | Methods of numerical modelling in physics using python. 4 | -------------------------------------------------------------------------------- /RK4_advancement.py: -------------------------------------------------------------------------------- 1 | from math import sin, pi 2 | from numpy import array, arange 3 | from pylab import plot, show, xlabel, ylabel 4 | import matplotlib.pyplot as plt 5 | 6 | t0 = 0.0 7 | t1 = 10.0 8 | N = 1000 # RK4 9 | h = (t1-t0)/N 10 | 11 | g = 9.81 # m/s/s 12 | l = 0.1 #10cm 13 | 14 | def f(r,t): 15 | theta = r[0] 16 | omgea = r[1] 17 | ftheta = omega 18 | fomega = -(g/l)*sin(r[0]) # calaculate angular acceleratino 19 | return array([ftheta,fomega], float) 20 | 21 | tpoints = arange(t0,t1,h) # timem values stored here 22 | thpoints = [] # theta values stored here 23 | opoints = [] # omega - angular velocity valyes stored here 24 | 25 | # initial conditions 26 | # theta0= 179.0*(pi/180) #starting angles 27 | theta0 = 150.0*(pi/180) 28 | omega0= 0.0*(pi/180) #starting velocity 29 | r = array([theta0, omega0], float) # startign vevtor r 30 | 31 | # for every time step... update time, calculate omega and addd it 32 | # position and velcotiy needs to be updated using the old values 33 | for t in tpoints: 34 | thpoints.append(r[0]) 35 | opoints.append(r[1]) 36 | 37 | # for RK4 , take 4 derivatives 38 | k1 = h*f(r,t) 39 | k2 = h*f(r + 0.5*k1, t+0.5) 40 | k3 = h*f(r + 0.5*k2, t+0.5*h) 41 | k4 = h*f(r + k3, t+h) 42 | 43 | r += (k1+2*k2+2*k3+k4)/6.0 44 | 45 | 46 | 47 | thdpoints = [180/pi*x for x in thpoints] 48 | 49 | plot(tpoints, thdpoints) 50 | 51 | xlabel("t") 52 | ylabel("theta in degrees") 53 | show() 54 | -------------------------------------------------------------------------------- /ball_euler_integration.py: -------------------------------------------------------------------------------- 1 | #bouncing ball example using euler integration 2 | 3 | # import stuff 4 | from numpy import array, arange 5 | from pylab import plot, show, xlim, ylim 6 | 7 | # define evolution equations 8 | 9 | g = 9.81 10 | 11 | def deriv(P): 12 | x = P[0] 13 | y = P[1] 14 | vx = P[2] 15 | vy = P[3] 16 | ax = 0.0 17 | ay = -g 18 | return array([vx,vy,ax,ay],float) 19 | 20 | # setup integration time and time resolution 21 | 22 | t0 = 0.0 23 | t1 = 10.0 24 | N = 10000 25 | dt = (t1-t0)/float(N) 26 | 27 | tpoints = arange(t0,t1,dt) 28 | 29 | # set up boundary conditions 30 | # walls at x0, x1, y0, y1 31 | 32 | x0 = 0.0 33 | x1 = 5.0 34 | y0 = 0.0 35 | y1 = 3.0 36 | 37 | # set up intial conditions 38 | 39 | p = array([0.0, 2.0, 1.5, 0.2],float) 40 | 41 | xpoints = [] 42 | ypoints = [] 43 | 44 | # iterate through steps 45 | # using Euler integration 46 | 47 | for t in tpoints: 48 | xpoints.append(p[0]) 49 | ypoints.append(p[1]) 50 | 51 | p += dt*deriv(p) 52 | 53 | # reflect off walls 54 | if p[0] < x0: 55 | p[0] = 2.0*x0 - p[0] 56 | p[2] = - p[2] 57 | 58 | if p[0] > x1: 59 | p[0] = 2.0*x1 - p[0] 60 | p[2] = - p[2] 61 | 62 | if p[1] < y0: 63 | p[1] = 2.0*y0 - p[1] 64 | p[3] = - p[3] 65 | 66 | if p[1] > y1: 67 | p[1] = 2.0*y1 - p[1] 68 | p[3] = - p[3] 69 | 70 | # show results 71 | xlim(x0 - 1, x1 + 1) 72 | ylim(y0 - 1, y1 + 1) 73 | 74 | # draw box 75 | boxx = [x0,x1,x1,x0,x0] 76 | boxy = [y0,y0,y1,y1,y0] 77 | plot(boxx,boxy, 'k-') 78 | 79 | #draw path 80 | plot(xpoints,ypoints) 81 | show() 82 | 83 | -------------------------------------------------------------------------------- /binomial_dist.py: -------------------------------------------------------------------------------- 1 | from math import factorial 2 | from numpy import power 3 | 4 | def binomial(n,k): 5 | if k == 0: 6 | return 1 7 | else: 8 | binom =factorial(n)/factorial(k)/factorial(n-k) 9 | return float(binom) 10 | 11 | 12 | def coinflip(n,k): 13 | # binomial probability function 14 | return binomial(n,k) * ((power(0.5,k))*(power(0.5,n-k))) 15 | 16 | coinflip(5,3) 17 | # 0.3125 18 | -------------------------------------------------------------------------------- /cartesian_coords.py: -------------------------------------------------------------------------------- 1 | def cartesian(r,theta): 2 | x = r*cos(theta) 3 | y = r*sin(theta) 4 | position = [x,y] # list with 2 elements 5 | return position 6 | 7 | # Note other iterations of the last line work too... 8 | return[x,y] 9 | return array([x,y], float) 10 | return x,y 11 | 12 | a,b = catesian(r,theta) #this works too 13 | -------------------------------------------------------------------------------- /data_histogram.py: -------------------------------------------------------------------------------- 1 | from numpy import loadtxt 2 | from matplotlib.pyplot import hist, show, title, xlabel, ylabel, grid 3 | 4 | data = loadtxt("sampledata.txt",float) #array of floats 5 | 6 | grid() 7 | xlabel("Number between 0-100") 8 | ylabel("Frequency of Number") 9 | title("Frequency of numbers in sampledata.txt") 10 | hist(data) 11 | show() 12 | -------------------------------------------------------------------------------- /erfc_gaussian_prob.py: -------------------------------------------------------------------------------- 1 | # EXAMPLE: CERN's fluke discovercies - variance 2 | 3 | # Expriment was 5-sigma, then 4.9-sigma, then 5.9-sigma, find the ODDS of the discovery being a fluke 4 | 5 | from math import erfc, sqrt 6 | # erfc = complementary error function 7 | 8 | print 0.5*erfc(5/sqrt(2.0)), "or 1 in", 2.0/erfc(5/sqrt(2.0))/,1.0e6, "million" 9 | 10 | print 0.5*erfc(4.9/sqrt(2.0)), "or 1 in ", 2.0/erfc(4.9/sqrt(2.0))/1.0e6, "million" 11 | 12 | print 0.5*erfc(5.9/sqrt(2)), "or 1 in", 2.0/erfc(5.9/sqrt(2.0)) / 1.0e6, "million" 13 | 14 | -------------------------------------------------------------------------------- /euler_advancement.py: -------------------------------------------------------------------------------- 1 | from math import sin, pi 2 | from numpy import array, arange 3 | from pylab import plot, show, xlabel, ylabel 4 | import matplotlib.pyplot as plt 5 | 6 | t0 = 0.0 7 | t1 = 3.0 8 | N = 3000000 # 3 million points to get good value 9 | h = (t1-t0)/N 10 | 11 | g = 9.81 # m/s/s 12 | l = 0.1 #10cm 13 | 14 | tpoints = arange(t0,t1,h) # timem values stored here 15 | thpoints = [] # theta values stored here 16 | opoints = [] # omega - angular velocity valyes stored here 17 | 18 | # initial conditions 19 | theta0= 179.0*(pi/180) #starting angles 20 | omega0= 0.0*(pi/180) #starting velocity 21 | r = array([theta0, omega0], float) # startign vevtor r 22 | 23 | # for every time step... update time, calculate omega and addd it 24 | # position and velcotiy needs to be updated using the old values 25 | for t in tpoints: 26 | thpoints.append(r[0]) 27 | opoints.append(r[1]) 28 | fomega = -(g/l)*sin(r[0]) # calaculate angular acceleratino 29 | r[0] += h*r[1] 30 | r[1] += h*fomega 31 | 32 | 33 | thdpoints = [180/pi*x for x in thpoints] 34 | 35 | plot(tpoints, thdpoints) 36 | 37 | xlabel("t") 38 | ylabel("theta in degrees") 39 | show() 40 | -------------------------------------------------------------------------------- /factorial_matlab.py: -------------------------------------------------------------------------------- 1 | # comparing factorial function to exp(power(x,1.5)/2) using matplotlib 2 | 3 | from numpy import log, exp, power 4 | from matplotlib.pyplot import figure, subplots,twinx, plot, show 5 | 6 | 7 | def factorial(x): 8 | placer = 1 9 | for i in range(1, x+1): 10 | placer *= i 11 | return placer 12 | 13 | def dashed(x): 14 | return exp(power(x,1.5)/2) 15 | 16 | # use linspace .. range produces a list.. 17 | x = range(0,21) 18 | y1 = log(map(factorial,x)) 19 | y2 = map(dashed,x) 20 | 21 | # subplots returns a tuple with a figure, and axes objects 22 | fig, ax1 = subplots() 23 | 24 | ax2 = ax1.twinx() 25 | ax1.plot(x, y1, '-') 26 | ax2.plot(x, y2, '--') 27 | -------------------------------------------------------------------------------- /factorials.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | # factorial is the product of all positive integers less than or equal to n 3 | # 5! = 5*4*3*2*1 = 120 4 | f = 1.0 5 | for k in range(1,n+1): 6 | f *= k # also f= k*f 7 | return f 8 | 9 | a = factorial(10) 10 | print a 11 | -------------------------------------------------------------------------------- /falling_Ball.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 2: Falling ball 3 | - Ball is dropped from a tower of height h. For input t, time - find the height it reaches 4 | - physics formula: uniformly accelerated motion 5 | 6 | ''' 7 | 8 | height = float(input("Enter the height of the tower:")) 9 | time = float(input("Enter the time interval:")) 10 | 11 | seconds = (9.81*t**2)/2 # double check this equation 12 | 13 | print "The height of the ball is", height-seconds, "meters" 14 | 15 | ''' 16 | -------------------------------------------------------------------------------- /float_comparison.py: -------------------------------------------------------------------------------- 1 | # increments floats 2 | #prints message at 7th indice 3 | 4 | 5 | from numpy import linspace 6 | 7 | epsilon = 1e-8 #margin of error 8 | 9 | for i in linspace(1.0, 10.0, 10): #linspace since floats 10 | if (abs(i - 7.0) < epsilon): 11 | # can't do equals with float comparisons 12 | print( "yay it worked at %f" % (i)) 13 | -------------------------------------------------------------------------------- /interpolation.py: -------------------------------------------------------------------------------- 1 | 2 | # interpolation 3 | from numpy import loadtxt, arange, zeros 4 | from pylab import * 5 | #hist, show, figure, ylim, plot, savefig 6 | 7 | y = loadtxt("testdata.txt",float) 8 | x0 = arange(0.0,len(y)) 9 | w = arange(0.0,len(y)) 10 | 11 | x = arange(0.0, float(len(y)-1), 0.001) 12 | fx = zeros(len(x),float) 13 | 14 | #for each sample x we want to plot 15 | for k in range(0,len(x)): 16 | #sum over data points x basis functions 17 | for i in range(0,len(y)): 18 | w[i] = 1.0 19 | for j in range(0,len(y)): 20 | if j != i: 21 | w[i] *= (x[k] - x0[j])/(x0[i] - x0[j]) 22 | fx[k] += w[i]*y[i] 23 | 24 | plot(x0,y,'o') 25 | xlim(-0.5,len(y)+0.5) 26 | show() 27 | 28 | xlim(-0.5,len(y)+0.5) 29 | plot(x0,y) 30 | plot(x0,y,'o') 31 | show() 32 | 33 | xlim(-0.5,len(y)+0.5) 34 | plot(x,fx) 35 | plot(x0,y) 36 | plot(x0,y,'o') 37 | show() 38 | -------------------------------------------------------------------------------- /large_data_sets.py: -------------------------------------------------------------------------------- 1 | psize = size*size 2 | p_av = zeros(psize, float) 3 | 4 | for i in range(0,size): 5 | for j in range(0,size): 6 | if i != j: 7 | p_av[(size*i) + j] = (marks[i]+marks[j])/ 2.0 8 | else: 9 | p_av[(size*i)+ j] = 0 10 | -------------------------------------------------------------------------------- /leapfrog_method.py: -------------------------------------------------------------------------------- 1 | # Solving differential equations 2 | # leapfrog method solution 3 | 4 | from math import sin, pi, sqrt 5 | from numpy import array,arange 6 | from pylab import plot, show, xlabel, ylabel, axes, xlim, ylim, grid 7 | import matplotlib.pyplot as plt 8 | 9 | ty0 = 0.0 10 | ty1 = 10.0 11 | t0 = ty0*3.15569e7 12 | t1 = ty1*3.15569e7 13 | N = 100 14 | h = (t1-t0)/N 15 | 16 | G = 6.673e-11 17 | M = 1.98e30 18 | 19 | def f(r,t): 20 | x = r[0] 21 | y = r[1] 22 | vx = r[2] 23 | vy = r[3] 24 | d = sqrt(x*x + y*y) 25 | ax = -x*G*M/d/d/d 26 | ay = -y*G*M/d/d/d 27 | return array([vx,vy,ax,ay],float) 28 | 29 | tpoints = arange(t0,t1,h) 30 | xpoints = [] 31 | ypoints = [] 32 | 33 | #two points start off the same 34 | r = array([1.49e11, 0.0, 0.0, 29800.0],float) 35 | r2 = array([1.49e11, 0.0, 0.0, 29800.0],float) 36 | 37 | #set r2 with RK4 38 | t = t0 39 | h2 = h/2.0 40 | k1 = h2*f(r, t) 41 | k2 = h2*f(r + 0.5*k1,t+0.5*h2) 42 | k3 = h2*f(r + 0.5*k2,t+0.5*h2) 43 | k4 = h2*f(r + k3,t+h2) 44 | r2 += (k1+2*k2+2*k3+k4)/6.0 45 | 46 | for t in tpoints: 47 | xpoints.append(r[0]) 48 | ypoints.append(r[1]) 49 | r += h*f(r2, t + h2) 50 | r2 += h*f(r, t + h) 51 | 52 | xau = [x/1.496e11 for x in xpoints] 53 | yau = [y/1.496e11 for y in ypoints] 54 | 55 | #plot(xpoints, ypoints) 56 | plot(xau, yau) 57 | 58 | axes().set_aspect('equal', 'datalim') 59 | xlim(-1.5,1.5) 60 | ylim(-1.5,1.5) 61 | xlabel("x (AU)") 62 | ylabel("y (AU)") 63 | #grid(2.0) 64 | show() 65 | -------------------------------------------------------------------------------- /lin_alg_solve.py: -------------------------------------------------------------------------------- 1 | from numpy import array 2 | from scipy.linalg import solve 3 | 4 | M = array([[1/5.,1,-1,0,1,1/2.], 5 | [1,0,-3,5,-2,-2], 6 | [1,1,2,-1,3,-2], 7 | [1,-1,-1,1,1./2,-1], 8 | [-1,5,-1,2,0,1], 9 | [-1,1,-1,0,0,-6]], float) 10 | 11 | answer = array([24.1312, 46.2798,-61.8372,31.1466,51.2106,-5.7008]) 12 | 13 | print solve(M, answer) 14 | 15 | 16 | # [-225.76371598 -88.06783231 -3.09392272 119.13851089 142.05030225 24.41510107] 17 | -------------------------------------------------------------------------------- /method_of_least_squares.py: -------------------------------------------------------------------------------- 1 | from pylab import scatter, xlabel,ylabel, xlim, ylim, savefig, plot, title 2 | from numpy import loadtxt, power 3 | 4 | data = loadtxt("millikan.txt",float) #Reads data points from milikan.txt file 5 | 6 | Ex_counter,Ey_counter,Exx_counter,Exy_counter = 0,0,0,0 # Set counters to start at 0 for sums 7 | 8 | # Calculate Ex, Ey, Exx, Exy - increment values to counters 9 | for i in range(0,6): 10 | Ex_counter += data[i,0] 11 | Ey_counter += data [i,1] 12 | Exx_counter += (data[i,0] * data[i,0]) 13 | Exy_counter += (data [i,1] * data[i,0]) 14 | Ex,Ey, Exx,Exy = Ex_counter/6,Ey_counter/6,Exx_counter/6,Exy_counter/6 15 | 16 | 17 | # Slope m, and y-intercept c for the line of best-fit 18 | m = (Exy - Ex*Ey) / (Exx - power(Ex,2)) 19 | c = ((Exx*Ey) - (Ex*Exy)) / (Exx - power(Ex,2)) 20 | 21 | print "For the line of best-fit, the slope was",m,"and the intercept was",c,"." 22 | print " " 23 | 24 | # Evalutes mxi + c, and stores values in fit_data 25 | fit_data =[] 26 | 27 | for i in range (0,6): 28 | fit_data.append((m*data[i,0]) + c) 29 | 30 | # Graph scatter plot dots, and the line of best fit 31 | x = data[:,0] 32 | y1 = data[:,1] 33 | y2 = fit_data 34 | 35 | scatter(x,y1) # from millikan.txt dataset 36 | plot(x,y2,"k-") # line of best fit 37 | 38 | title(" Millikan's experimental value for Planck's constant ") 39 | xlabel(" Frequency (Hz)") 40 | ylabel(" Voltage (eV) ") 41 | 42 | savefig('figure.png') 43 | -------------------------------------------------------------------------------- /newton.py: -------------------------------------------------------------------------------- 1 | # working secant method.. (newton's method) 2 | 3 | #tolerance 4 | tol=1e-10 5 | 6 | #newton method - secants 7 | def newton(func, x0): 8 | p0 = x0 9 | if x0 >= 0: 10 | p1 = x0*(1 + 1e-4) + 1e-4 11 | else: 12 | p1 = x0*(1 + 1e-4) - 1e-4 13 | q0 = func(*((p0,) )) 14 | q1 = func(*((p1,) )) 15 | for iter in range(50): 16 | if q1 == q0: 17 | if p1 != p0: 18 | msg = "Tolerance of %s reached" % (p1 - p0) 19 | return (p1 + p0)/2.0 20 | else: 21 | p = p1 - q1*(p1 - p0)/(q1 - q0) 22 | if abs(p - p1) < tol: 23 | return p 24 | p0 = p1 25 | q0 = q1 26 | p1 = p 27 | q1 = func(*((p1,) )) 28 | 29 | 30 | #function 31 | def P(x): 32 | return 924*x**6 - 2772*x**5 + 3150*x**4 - 1680*x**3 + 420*x**2 - 42*x + 1 33 | 34 | 35 | x1_array = [0.01, 0.15, 0.35, 0.6, 0.7, 0.9] 36 | 37 | #print roots 38 | for i in x1_array: 39 | print "The root is at", newton(P,i), "and f(x) at the root is", P(i) 40 | 41 | 42 | -------------------------------------------------------------------------------- /plotting_function.py: -------------------------------------------------------------------------------- 1 | # Plotting function cos(power(n,2.0)) /(1.0 + (power(n,2.0))) 2 | 3 | from matplotlib.pyplot import plot, show, title, xlabel, ylabel,grid,xticks,yticks,xlim, ylim 4 | from numpy import cos, power, linspace, arange 5 | 6 | def function(n): 7 | return cos(power(n,2.0)) /(1.0 + (power(n,2.0))) 8 | 9 | x = linspace(-5,+5,10) 10 | y = map(function,x) 11 | 12 | xlabel("input") 13 | ylabel("output of function") 14 | ylim(-0.5,1.0) 15 | xlim(-10,11) 16 | title("Python plotting") 17 | xticks(range(-10,11), range(-10,11)) 18 | 19 | 20 | plot(x,y,"r-") 21 | show() 22 | -------------------------------------------------------------------------------- /prime_numbers.py: -------------------------------------------------------------------------------- 1 | # program that returns a list of all the prime numbers in n 2 | def factors(n): 3 | factorlist = [] 4 | k = 2 #smallest prime number 5 | while k <= n : 6 | while n%k == 0: 7 | factorlist.append(k) 8 | n /= k 9 | k += 1 10 | return factorlist 11 | 12 | 13 | def factorial(n): 14 | if n == 1: 15 | return 1 16 | else: 17 | return n*factorial(n-1) 18 | -------------------------------------------------------------------------------- /reflection.py: -------------------------------------------------------------------------------- 1 | from math import cos,sin,pi 2 | from numpy import array,arange,sin,cos,linspace,zeros 3 | from pylab import plot,show,ylim 4 | 5 | #step 1 6 | 7 | closedint = range(101) # 0 to 100, so 101 values 8 | x = (pi/100)*array(closedint,float) 9 | 10 | 11 | plot(x,sin(x)) 12 | ylim(0.0,1.1) 13 | 14 | #step 2 15 | xt = 1.1 16 | yt = sin(xt) 17 | dx = 0.3 18 | slope = cos(xt) # = dy/dx 19 | normal = -1/slope 20 | dy = dx*slope 21 | dy2 = dx 22 | dx2 = dy2/normal 23 | 24 | tangx = array([xt - dx, xt, xt+dx],float) 25 | tangy = array([yt - dy, yt, yt+dy],float) 26 | plot(tangx,tangy,'k-') 27 | 28 | normx = array([xt -dx2, xt, xt+dx2],float) 29 | normy = array([yt -dy2, yt, yt+dy2],float) 30 | plot(normx,normy,'k-') 31 | 32 | show() 33 | -------------------------------------------------------------------------------- /riemann_sums.py: -------------------------------------------------------------------------------- 1 | #use Riemann Sums to estimate a definite integral 2 | 3 | 4 | # from x=-2 to x=+2 5 | # f(x) = cos(power(x,2)) / (1 + power(x,2)) 6 | 7 | # We can evaluate a definite integral using Riemann Sums method 8 | 9 | from math import cos 10 | from numpy import linspace, sum, power, array 11 | 12 | 13 | # x--> from -2 to 2 14 | # divide the x-axis to 100 mini sections to make our dx BOX WIR 15 | dx = (4.0)/100 #float 16 | 17 | #write out our x-axis ticks - need linspace.. floats 18 | 19 | x_list = linspace(-2,2-dx,100) # subtract dx since not in calculations 20 | 21 | #integral 22 | def f(x): 23 | return cos(power(x,2))/ (1+ power(x,2)) 24 | 25 | # we have dx, x_list, and f(x) 26 | # find y values for all the x_list values.. 27 | # used map but map ==> list --> need array 28 | 29 | y_list = map(f, x_list) #returns a list. but we want an array 30 | y_list = array(y_list) 31 | 32 | 33 | #one rectangle area 34 | single_rec_area = dx * array(map(f,y_list)) 35 | 36 | 37 | #sum up all the areas 38 | print single_rec_area.sum() 39 | -------------------------------------------------------------------------------- /rydberg.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example 1: Rydberg Equation used in Atomic Physics to find the wavelengths of spectra lines for Hydrogen atoms. 3 | 4 | - inputs: R, m, n, R= constant, m and n are integers representing the principle quantum numbers of the orbitals occupied BEFORE/AFTER the quantum leap 5 | 6 | - output: invlambda, the first few transitin wavelengths of the EM radiation emitted 7 | ''' 8 | 9 | 10 | R= 1.097e-2 11 | 12 | for m in [1,2,3]: 13 | print "Series for m=", m 14 | 15 | for k in [1,2,3,4,5]: # WHERE K =5 COME FROM??? 16 | n = m+k 17 | invlambda = R*(1/m**2-1/n**2) 18 | print " ",1/invlambda," nm" 19 | 20 | 21 | ''' 22 | ('Series for m=', 1) 23 | 91.1577028259 nm 24 | 91.1577028259 nm 25 | 91.1577028259 nm 26 | 91.1577028259 nm 27 | 91.1577028259 nm 28 | ('Series for m=', 2) 29 | 30 | ''' 31 | -------------------------------------------------------------------------------- /time_counter.py: -------------------------------------------------------------------------------- 1 | import time 2 | t0 = time.time() 3 | sum = 0.0 4 | 5 | for i in range(0,40000000): 6 | sum += i 7 | print sum 8 | 9 | print time.time() - t0, "seconds wall time" 10 | -------------------------------------------------------------------------------- /transformation_points.py: -------------------------------------------------------------------------------- 1 | from numpy import sin, cos 2 | 3 | def translatepoints(x,y,xt,yt): 4 | xr = x+xt 5 | yr = y+yt 6 | return xr,yr 7 | 8 | def rotatepoints(x,y,theta): 9 | xr = cos(theta)*x - sin(theta)*y 10 | yr = sin(theta)*x + cos(theta)*y 11 | return xr,yr 12 | 13 | def scalepoints(x,y,scale): 14 | xr = scale*x 15 | yr = scale*y 16 | return xr,yr 17 | 18 | -------------------------------------------------------------------------------- /vector_norm.py: -------------------------------------------------------------------------------- 1 | #norm (length or size) of a vector 2 | 3 | norm = v[0]*v[0] + v[1]*v[1] + v[2]*v[2] #v = vector 4 | 5 | def norm(v) 6 | n = v[0]*v[0] + v[1]*v[1] + v[2]*v[2] 7 | return n 8 | 9 | x = norm(v) #to use the function, define it as "x" 10 | --------------------------------------------------------------------------------