Archives for 11 Sep,2009

You are browsing the site archives by date.

Python: Making multi depth directories

If you try and write a file to something like ‘subfolder/file.txt’ in python it wont automatically create the subfolder for you and it will fail with:

IOError: [Errno 2] No such file or directory: 'test2/file.txt'

I imagine this is deliberate as you don’t want to be accidentally creating folders. So to make a single folder we import the os module, and use the mkdir command

import os
os.mkdir('newfolder')

This is good, but if we try and make a subdirectories using the single command then it will fail as this command will only try and create the last directory in the string you pass. IE: if you pass dir1/dir2/dir3 it will assume dir1 and dir2 already exist and try to make dir3, which will fail with:

OSError: [Errno 2] No such file or directory: 'dir1/dir2/dir3'

So in order for this to work we would need to make it recursivly create subdirectories, but thankfully someone already went to the trouble for us with ‘supermakedir’ or makedirs.

import os
os.makedirs('dir1/dir2/dir3')

So this is probably useful enough for most people, but I needed to create folders in order for a file to get dropped in it, however I was only given the full path for the file not seperated into filename and directory path.

So I made the following function that accepts an input such as ‘dir1/dir2/dir3/filename.txt’ and cuts it into the folder path using os.path.dirname(filename), and then checks if the folder exists using os.path.exists(folder), and then makes the folders if they don’t already exist.

def mkdirnotex(filename):
	folder=os.path.dirname(filename)
	if not os.path.exists(folder):
		os.makedirs(folder)
Read More

Python: Calculating pi using random numbers

During my undergraduate degree I wrote a program in fortran 95 to calculate pi using random numbers. My aim is to rewrite it efficiently in python. I know its a terrible way to calculate pi, and there are much better ways to do it but its fun!

First I’ll explain the maths so you can visualise what’s going on. As we should know _pi_ is the ratio of circle’s radius to its circumference, which is conveniently the same as the ratio of a circle’s area to the square of its radius (wiki…)

So what we are going to be doing is picking lots of random coordinates in an x-y grid and calculating if they are within the circle or the square.
python-pi-random-numbers-1
We will assign the radius to be 1, because that makes it easy to work with. By default a random number in python ( random() ) will return a floating point number between 0 and 1. To test if a point is within a circle we simply use Pythagoras.

So if the sqrt(a**2+b**2)<=1 then the point lies inside the circle’s radius. In the diagram above we see that point A lies within the circle, and point B lies outside the circle.

We can really don’t need to use the whole circle as it has symmetry, so we can just take a quartre, which makes the generating of random numbers easier as you only need to use a random number for x and y between 0 and 1, rather than -1 and 1. It will look like the diagram below.

python-pi-random-numbers-2

Now for a confusing bit of maths. We are calculating the ratio of the area of a circle to the area of a square.

# Area of circle
A=pi*r**2
# where r = 1
A = pi
# Area of square
A = l ** 2
# in this case (see diagram) our square's length is twice the radius
l=2*r
A=(1+1)**2 = 4

#Therefore our ratio will be pi : 4.
# Which means we must multiply our result by four to get pi.

Final version (efficient for using)

from random import *
from math import sqrt
inside=0
n=1000
for i in range(0,n):
	x=random()
	y=random()
	if sqrt(x*x+y*y)<=1:
		inside+=1
pi=4*inside/n
print pi

Below we can see the values it creates

n	calc	error
1	4.00000000	0.73686317
10	3.60000000	0.45840735
100	3.24000000	0.09840735
1000	3.06400000	-0.07759265
10000	3.16160000	0.02000735
100000	3.14140000	-0.00019265
1000000	3.14293600	0.00134335
10000000	3.14117920	-0.00041345

pi-random-number-error

So we can see that the program quickly solves pi to about two decimal places, but it is a terribly inefficient method and will struggle to get much more accuracy than this.

Resources to check out:
This blog post – Solves pi via taylor series expansion
Super pi – Program that calculate pi often used for benchmarking

Read More