473,387 Members | 1,834 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,387 software developers and data experts.

My first Python program.. Calculating pi geometrically.


Hi, I'm having fun learning Python and want to say thanks to everyone
here for a great programming language.

Below is my first Python program (not my first program) and I'd
apreciate any feedback on how I might do things differently to make it
either more consice, readable, or faster. ie... are there better ways
to do it in Python?

It won't break any records for calculating pi, that wasn't my goal,
learning Python was. But it might be good for testing floating point
and decimal performance. It also might make a good demo of the same.
Anyway, here it is, any feedback would be apreciated.

_Ron


"""
## Program name: pi10.py
## Author: Ronald R. Adam
## Version: 1.01
## Date: 11/01/2003
##
## Email: ra****@tampabay.rr.com or ro*@ronadam.com
##
## This program calculates Pi using a geometric progression of
## triangles. The program is written in Python and requires
## the gmpy math module in order to use extended floating point
## precision.
##
## This is a rough diagram of the location of the points used.
##
## |
## A* --.__
## | \ `-._
## | \ `* D
## | \ / \
## | C * \
## | . \ \
## | . \ |
## | . \ |
## *---------------*---
## O B
##
## Pint C is the mid point of line AB.
## Point D is on the circle 90 degrees to line AB from point C.
##
## Area = OAB*4 + CDB*8 + ...
##
## ... Point A is relocated to point D and then new points
## C and D are calculated. This is repeated ...
##
## ... + CDB*16 + CDB*32 + ... (Repeats until done)
##
## When it's done, the last line of AB length multiplied by with
## the number of sides (2^n) is used to calculate the
## circumference, and then calculate pi again to check the result.
##
## Pi to 10,000 digits take about 5 minutes on my desktop computer.
## I'm not sure what the maximum is so drop me an email if you get
## some really long sequences. This program progrssivly slows down
## as the number of digits increases because it uses the entire
## length of each floating point number.
"""

import gmpy
import datetime
import time

print """
Pi10.py Version 1.0, by Ronald R. Adam

This program calculates Pi by using a geometric progression
of triangles to measure the area of a circle with a radius of 1.

"""

d=1
while d>0:

try:
d = gmpy.mpz(raw_input('Number of decimal digits: '))
except:
break

# Estimate the precision needed.
# This may need some adjustment.
p = int(d*3.325)+16 # gmpy precision value

start = time.clock()
t_old = start
print 'Calculating Pi ...'
# set variable values and precision.
n = gmpy.mpz('2') # number of triangles
radius = gmpy.mpf('1.0',p) # radius
area = gmpy.mpf((radius*radius)/2 * 2**n) #area=(base*height)/2*4
Ax, Ay = gmpy.mpf('0.0',p) , radius # point A
Bx, By = radius , gmpy.mpz('0') # point B
Cx = Cy = gmpy.mpf('0.0',p) # point C
OC = CD = CB = gmpy.mpf('0.0',p) # lines OC,CD,CB
vx = vy = gmpy.mpf('0.0',p) # vectors of line CD

# Loop until additions to area are too small to calculate
# using the requested precision + 2 digits.
p_area = gmpy.mpf('0.0',p)
while gmpy.fdigits(p_area,10,d+2) <> gmpy.fdigits(area,10,d+2):
p_area = area

Cx, Cy = (Ax+1)/2, Ay/2 # find midpoint of line AB
OC = gmpy.fsqrt(Cx**2 + Cy**2) # find length of line OC
CD = radius - OC # find length of line CD
CB = gmpy.fsqrt((Bx-Cx)**2+Cy**2) # find length of line CB
n += 1 # double triangles 2^(n+1)
area = area + (CB*CD/2) * 2**n # add trianges BCD * 2^n
vx = CD * Cx/OC # find x vector of line CD
vy = CD * Cy/OC # find y vector of line CD
Ax, Ay = Cx+vx, Cy+vy # Ax,Ay = Dx,Dy

t = time.clock()
if t > t_old+10:
t_old = t
print 'Exceeding 2^', n ,'sides ...'
# pi1 = area/radius^2
pi1 = gmpy.fdigits(area) # use (area/radius**2) if radius <>1
# pi2 = circumference /(2*radius)

pi2=gmpy.fdigits((gmpy.fsqrt((Bx-Ax)**2+(By-Ay)**2)*2**n)/(2*radius))

# Compare the two above calculations to each other
# and copy the matching & requested digits to the
# result string.
pi = ''
k = 0
while pi1[k] == pi2[k]:
pi = pi+pi1[k]
k += 1
pi = pi[0:int(d+2)]
# Report the result
print
print 'Pi =\n',pi
print
print len(pi)-2, 'decimal places'
print 'Radius =', radius
print '2^', n, ' sides'
stop = time.clock()
print 'Elapsed time:',datetime.timedelta( 0, stop-start)
print

# End #

Jul 18 '05 #1
5 8781
On Sat, 01 Nov 2003 06:49:55 GMT, Ron Adam <ra****@tampabay.rr.com>
wrote:

Hi, I'm having fun learning Python and want to say thanks to everyone
here for a great programming language.

Below is my first Python program (not my first program) and I'd
apreciate any feedback on how I might do things differently to make it
either more consice, readable, or faster. ie... are there better ways
to do it in Python?

It won't break any records for calculating pi, that wasn't my goal,
learning Python was. But it might be good for testing floating point
and decimal performance. It also might make a good demo of the same.
Anyway, here it is, any feedback would be apreciated.

_Ron

BTW, I do know I can do this and get pi much much faster.
import gmpy
gmpy.pi(1000000)


That gives me over 300,000 decimal places in 2 to 3 minutes.

Which is very impressive. :-)

Doing it geometrically was strictly a learning exercise. And I did
learn quite a bit by doing it.

_Ron
Jul 18 '05 #2
Ron Adam wrote:
Doing it geometrically was strictly a learning exercise. And I did
learn quite a bit by doing it.


And you only scratched the surface of what Python offers you :-)
While it's nice to hear that you learned a lot by making this
arithmetic python program, it certainly is not the most
inspiring thing that Python is capable of...

I even think you learned more about calculating Pi than you
did about programming in Python ;-)

--Irmen

Jul 18 '05 #3
On Sat, 01 Nov 2003 12:35:45 +0100, Irmen de Jong
<irmen@-NOSPAM-REMOVETHIS-xs4all.nl> wrote:
Ron Adam wrote:
Doing it geometrically was strictly a learning exercise. And I did
learn quite a bit by doing it.


And you only scratched the surface of what Python offers you :-)
While it's nice to hear that you learned a lot by making this
arithmetic python program, it certainly is not the most
inspiring thing that Python is capable of...

I even think you learned more about calculating Pi than you
did about programming in Python ;-)

--Irmen


The challenging parts were, figuring out how to do the calculation
without using sin or cos, (nice geometry refresher), getting the gmpy
module to work and how to set the precision, and working out by trial
and error the precision calculation. If there is a formula to
convert digits of precision to bits of precision, I'd like to know.
And the last was to figure out how to use the clock and timedelta
functions.

Other interesting things I learned was how to convert to and from
stings, use slices, and for-in loops are very fast for small lists,
but can eat up a lot of memory, hit the swap file and be extremely
slow for large lists. For-in loops aren't suited for everything.

And yes, before I started, I did not know how to calculate pi. So you
are right about that. ;-) That was an interesting subject in it
self.

Overall, it was a very good learning project.

_Ron



Jul 18 '05 #4
Ron Adam wrote:
On Sat, 01 Nov 2003 12:35:45 +0100, Irmen de Jong
<irmen@-NOSPAM-REMOVETHIS-xs4all.nl> wrote:
Ron Adam wrote:
Doing it geometrically was strictly a learning exercise. And I did
learn quite a bit by doing it.


And you only scratched the surface of what Python offers you :-)
While it's nice to hear that you learned a lot by making this
arithmetic python program, it certainly is not the most
inspiring thing that Python is capable of...

I even think you learned more about calculating Pi than you
did about programming in Python ;-)

--Irmen


The challenging parts were, figuring out how to do the calculation
without using sin or cos, (nice geometry refresher), getting the gmpy
module to work and how to set the precision, and working out by trial
and error the precision calculation. If there is a formula to
convert digits of precision to bits of precision, I'd like to know.
And the last was to figure out how to use the clock and timedelta
functions.

Other interesting things I learned was how to convert to and from
stings, use slices, and for-in loops are very fast for small lists,
but can eat up a lot of memory, hit the swap file and be extremely
slow for large lists. For-in loops aren't suited for everything.

And yes, before I started, I did not know how to calculate pi. So you
are right about that. ;-) That was an interesting subject in it
self.

Overall, it was a very good learning project.

_Ron


As I recall, Ron, your method is the same one used by Archimedes when he
computed PI.
http://itech.fgcu.edu/faculty/clinds...rchimedes.html
The method of diminishing triangles is SO similar to Gauss & Newton's
method of diminishing rectangles one wonders how much faster the scientific
advances of Man would have occurred if Archimedes had gone on to develop
Calculus.

--

-
GrayGeek
Jul 18 '05 #5
On Sat, 01 Nov 2003 19:09:42 GMT, GrayGeek <jk********@FISHneb.rr.com>
wrote:
Ron Adam wrote:
On Sat, 01 Nov 2003 12:35:45 +0100, Irmen de Jong
<irmen@-NOSPAM-REMOVETHIS-xs4all.nl> wrote:
Ron Adam wrote:

Doing it geometrically was strictly a learning exercise. And I did
learn quite a bit by doing it.

And you only scratched the surface of what Python offers you :-)
While it's nice to hear that you learned a lot by making this
arithmetic python program, it certainly is not the most
inspiring thing that Python is capable of...

I even think you learned more about calculating Pi than you
did about programming in Python ;-)

--Irmen


The challenging parts were, figuring out how to do the calculation
without using sin or cos, (nice geometry refresher), getting the gmpy
module to work and how to set the precision, and working out by trial
and error the precision calculation. If there is a formula to
convert digits of precision to bits of precision, I'd like to know.
And the last was to figure out how to use the clock and timedelta
functions.

Other interesting things I learned was how to convert to and from
stings, use slices, and for-in loops are very fast for small lists,
but can eat up a lot of memory, hit the swap file and be extremely
slow for large lists. For-in loops aren't suited for everything.

And yes, before I started, I did not know how to calculate pi. So you
are right about that. ;-) That was an interesting subject in it
self.

Overall, it was a very good learning project.

_Ron


As I recall, Ron, your method is the same one used by Archimedes when he
computed PI.
http://itech.fgcu.edu/faculty/clinds...rchimedes.html
The method of diminishing triangles is SO similar to Gauss & Newton's
method of diminishing rectangles one wonders how much faster the scientific
advances of Man would have occurred if Archimedes had gone on to develop
Calculus.


Yes, the concept is the same, but slightly different method. All
the examples I found used trig functions to do it with or used ratios
related to trig functions. I used vectors to get around that.

How much did calculus contributed to advances in mankind after it was
developed? I think other developments in production methods and
economics had a bigger impact and didn't require calculus.

Correction, a quick search found this....
http://www-gap.dcs.st-and.ac.uk/~his..._calculus.html

This shows calculus was developed over quite a long time in
conjunction with, and driven by developments in production, which in
turn were related to economics.

But 2,500 years is a long time ago and who knows what would have
happened? What would have happened if the telescope was invented
sooner? :-)

Something interesting about gmpy accuracy is after calculating pi to
10,000 digits and displaying the entire floating point number, only
the last 4 digits are off due to rounding errors. I think that is
exceptional and only occasionally are the last 5 digits not correct.
I get around that by calculating at least 5 extra digits and then
truncating.

_Ron
Jul 18 '05 #6

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

Similar topics

7
by: Catalin | last post by:
How can I make executables with python? I found some utilities that claim they can do something like that like Installer and py2exe but they actualy pack the code in a huge arhive! This solves the...
10
by: 2mc | last post by:
I'm new to Python and to Numerical Python. I have a program written in another program that used arrays extensively. I'm trying to convert to Python. Assume an array in Numerical Python, the...
24
by: Matt Feinstein | last post by:
Hi all-- I'm new to Python, and was somewhat taken aback to discover that the core language lacks some basic numerical types (e.g., single-precision float, short integers). I realize that there...
1
by: Jung Joon Park | last post by:
Hi everyone. I am JJ Park. I got some questions in C++. First of all, my English is not perfect, because I am foreigner. I have got C++ code, which have no syntex error in Visual C++ ver6.0...
3
by: Padraig | last post by:
Hi all, Just a quick question... when I try to install Python on Windows Vista Beta 2 the installer seems to hang after I select the destination folder, saying that it will "return when it has...
83
by: Licheng Fang | last post by:
Hi, I'm learning STL and I wrote some simple code to compare the efficiency of python and STL. //C++ #include <iostream> #include <string> #include <vector> #include <set> #include...
11
by: efrat | last post by:
Hello, I'm planning to use Python in order to teach a DSA (data structures and algorithms) course in an academic institute. If you could help out with the following questions, I'd sure...
50
by: Gosi | last post by:
It is quite easy to call J from Python http://groups.google.com/group/J-Programming/browse_thread/thread/5e84b75667f5f64e
10
by: Lorenzo Di Gregorio | last post by:
Hello, I've been using Python for some DES simulations because we don't need full C speed and it's so much faster for writing models. During coding I find it handy to assign a variable *unless...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.