Showing posts with label pi. Show all posts
Showing posts with label pi. Show all posts

Sunday, June 26, 2016

A Pythonic ratio for pi (or, Py for pi :)

By Vasudev Ram

Py


Pi image attribution

A Python built-in method can be used to find a ratio (of two integers) that equals the mathematical constant pi. [1]

This is how:
from __future__ import print_function
Doing:
dir(0.0) # or dir(float)
gives (some lines truncated):
'__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 
'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']
>>>
from which we see that as_integer_ratio is a method of float objects. (Floats are objects, so they can have methods.) So:
>>> import math

>>> tup = math.pi.as_integer_ratio()
>>> tup
(884279719003555, 281474976710656)

>>> tup[0] / tup[1]
3.141592653589793

>>> print(sys.version)
3.6.0a2 (v3.6.0a2:378893423552, Jun 14 2016, 01:21:40) [MSC v.1900 64 bit (AMD64
)]
>>>
I was using Python 3.6 above. If you do this in Python 2.7, the "/" causes integer division (when used with integers). So you have to multiply by a float to cause float division to happen:
>>> print(sys.version)
2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)]

>>> tup[0] / tup[1]
3L
>>> 1.0 * tup[0] / tup[1]
3.141592653589793
>>>
[1] There are many Wikipedia topics related to pi.
Also check out a few of my earlier math-related posts (including the one titled "Bhaskaracharya and the man who found zero" :)

The second post in the series on the uses of randomness will be posted in a couple of days - sorry for the delay.

- Vasudev Ram - Online Python training and consulting

Signup to hear about my new courses and products.

My Python posts     Subscribe to my blog by email

My ActiveState recipes