473,379 Members | 1,544 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,379 software developers and data experts.

Help with if statement

I can't get my "if" statement to work indicated below.
What happens is no matter what the value random is, neg gets incremented by 1.

This is actually my first time programming in Python. Any help is appreciated.

TIA
Gene

import random
uniform = random.uniform
neg = 0
N = int(raw_input("Enter number of random generations, N: "))

for x in range(0,N):
random = uniform(-1, 1)
print random
if random < 1.0: <--- Not working
neg = neg+1
print neg
pi = 4.*(neg/N)
print 'The value of Pi is ', pi
Jul 18 '05 #1
6 1237
ji*******@yahoo.com (Jikosan) writes:
for x in range(0,N):
random = uniform(-1, 1)
random is a number between -1 and +1. It's always < 1.
print random
if random < 1.0: <--- Not working
neg = neg+1


You mean "if random < 0.0:".
Jul 18 '05 #2
>>>>> "Jikosan" == Jikosan <ji*******@yahoo.com> writes:
I can't get my "if" statement to work indicated below. What happens is no
matter what the value random is, neg gets incremented by 1.
for x in range(0,N):
random = uniform(-1, 1)
print random
if random < 1.0: <--- Not working
neg = neg+1


Since uniform will return numbers in the interval [-1, 1), all instances of
random will be less than 1.0. May be you meant to say random < 0.0?

Ganesan

--
Ganesan R (rganesan at debian dot org) | http://www.debian.org/~rganesan/
1024D/5D8C12EA, fingerprint F361 84F1 8D82 32E7 1832 6798 15E0 02BA 5D8C 12EA
Jul 18 '05 #3
Ya, I had mis-read the assignment.

The code is fully functional now. If anyone is curious, here it is.

import random #import random number generator library
import math #import math library

file=open('C:\Python\output.txt', 'w')
a, b = -1.0, 1.0 #set boundary conditions
for N in range(0, 100001, 25): # 100,000 trials at steps of 25
if N == 0: #This corrects for N=0
N = 1
onecheck = 0
for n in range(0,N): #generate (x,y) numbers 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)) #calculate 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: #This is to prevent 'log 0' errors
pi == 1.0
log = str(math.log(N, 10))
file.write(str(math.log(N, 10)))
file.write(' ')
file.write(str(math.log(pi, 10)))
file.write('\n')
file.close()
Jul 18 '05 #4
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()
Jul 18 '05 #5
"Jikosan" <ji*****@myrealbox.com> writes:
for N in range(0, 100000, 25):
For such a large list, you should xrange instead of range. That will
use less memory.
c = math.sqrt(math.pow(x,2.0) + math.pow(y,2.0))
You should use "c = math.sqrt(x*x + y*y)" which is both faster and
more flexible: math.pow(x,2.0) happens to work ok here, but can throw
an error in some implementations if x is negative.
pi = 4.0*(onecheck*math.pow(N,-1))
You can say "pi = (4.0 * onecheck) / N" here. That's faster and more
straightforward.
#Convert pi and N to log10 and write to a file to graph on Excel.


Why are you going to graph log(N) vs log(pi)? Do you expect them
to have an exponential relationship? If not, log(N) vs pi, instead
of log(pi), may make more sense.
Jul 18 '05 #6
"Paul Rubin" <http://ph****@NOSPAM.invalid> wrote in message
news:7x************@ruckus.brouhaha.com...

Thanks Paul. I so far have only been learning Python from the tutorial and
greatly appreciate your tips.

|
| > #Convert pi and N to log10 and write to a file to graph on Excel.
|
| Why are you going to graph log(N) vs log(pi)? Do you expect them
| to have an exponential relationship? If not, log(N) vs pi, instead
| of log(pi), may make more sense.

Because my professor wants us to graph it log(N) vs log(pi).
Actually, it's log [P(N) - pi/4] vs log N. I misread the question again last
night.
Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

46
by: Kingdom | last post by:
In my data base I have a list of componet types e.g. type A - I have 8 off - type B I have 12 off etc. I'm using Set objRS = objDC.Execute("Select DISTINCT Component_Type FROM Parts_Table") ...
6
by: Mark Reed | last post by:
Hi all, I am trying to learn a little about programming (I know next to nothing so far) and have found some code which hides the toolbars. However, this bit of code is a little too effective and...
8
by: drose0927 | last post by:
Please help! I can't get my program to exit if the user hits the Escape button: When I tried exit(EXIT_SUCCESS), it wouldn't compile and gave me this error: Parse Error, expecting `'}''...
5
by: Jesee | last post by:
I am reading Jeffrey Richter's book "Applied Microsoft .NET Framework programming",i came across "Exception handing". Page 405 says "If the stack overflow occurs within the CLR itself,your...
11
by: Scott C. Reynolds | last post by:
In VB6 you could do a SELECT CASE that would evaluate each case for truth and execute those statements, such as: SELECT CASE True case x > y: dosomestuff() case x = 5: dosomestuff() case y >...
2
by: Greg Corradini | last post by:
Hello All, A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. Among other things, both scripts create new tables, perform a query and then populate the tables with data in a...
6
by: redashley40 | last post by:
This is my first attempt in SQL and PreparedStatement I have add the PreparedStatement and I'm not to sure if I'm doing it correctly. When I do a test run on Choose 1 ,or 2 I get this error. Error...
2
by: rookiejavadude | last post by:
I'm have most of my java script done but can not figure out how to add a few buttons. I need to add a delete and add buttong to my existing java program. Not sure were to add it on how. Can anyone...
0
by: RCapps | last post by:
When running the below SQL Query I keep getting the following error: Server: Msg 4924, Level 16, State 1, Line 1 ALTER TABLE DROP COLUMN failed because column 'ContractDef' does not exist in table...
2
by: kya2 | last post by:
I am not able to create following store procedure. CREATE PROCEDURE DBSAMBA.InsertDeleteBatch(OUT norows INT ) RESULT SETS 1 LANGUAGE SQL BEGIN part1 DECLARE TOTAL_LEFT INT DEFAULT 0; ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.