# Help with if statement

Jikosan jikosan at myrealbox.com
Sun Jan 11 10:49:41 CET 2004

```I got it working. I had originally misread the prompt.

Here's the code I finally got working. It calculates PI using the Monte
Carlo method.
I have to graph log N vs log PI, which explains the last few lines of the
program.

Gene

#HW1 - 1.5.2
#This code was written in the Python programming language.

import random   #Loads the random number generator library.
import math     #Loads the math library.

file=open('output.txt', 'w')    #Identifies output file.
a, b = -1.0, 1.0                #Sets the boundary conditions for (x,y).
for N in range(0, 100000, 25):  #4000 trials, 1<= N <= 100000 at steps of
25.
if N == 0:
N = 1
onecheck = 0
for n in range(0,N):        #This for loop generates (x,y) sets N times.
xrand = random.random()
yrand = random.random()
x = a * (1.0-(xrand)) + b*(xrand)
y = a * (1.0-(yrand)) + b*(yrand)
c = math.sqrt(math.pow(x,2.0) + math.pow(y,2.0))    #Calculates the
distance to origin.
if c < 1:
onecheck = onecheck+1
pi = 4.0*(onecheck*math.pow(N,-1))  #This is to calculate P(N), the
ratio of points whose
#distance is less than 1 to the
total number of trials.
if pi == 0.0:   #Prevent 'log 0' calculation errors
pi == 1.0

#Convert pi and N to log10 and write to a file to graph on Excel.
file.write(str(math.log(N, 10)))
file.write('    ')
file.write(str(math.log(pi, 10)))
file.write('\n')
file.close()

```