Coding

Pi in Python: Using math.pi (With Circle Examples)

In Python, pi is math.pi: run import math and then use math.pi, which is the float 3.141592653589793. It is part of the standard library, so there is nothing to install.

import math

print(math.pi)

Example output:

3.141592653589793

How to import pi

There are two common ways. Both give you the same value.

import math
print(math.pi)

from math import pi
print(pi)

The first keeps the math. prefix, which makes it obvious where the constant comes from. The second is shorter, which helps in long formulas. Avoid from math import *: it pulls every name from the module into yours, and a variable called pi or e elsewhere in your code can silently overwrite the constant.

A common mistake is typing pi without importing it. Python then stops with NameError: name 'pi' is not defined. The fix is one of the two imports above.

What math.pi actually is

The Python documentation defines math.pi as "the mathematical constant π = 3.141592…, to available precision". "Available precision" means a float. Python floats are IEEE 754 double-precision values with 53 bits of precision, so math.pi is the closest float to pi, not pi itself. It prints as 3.141592653589793, which is 15 decimal places. Real pi continues forever without repeating, so no float can hold it exactly.

For almost all practical work, this is plenty. The error is on the order of one part in 2**53 per operation, as the tutorial on floating-point arithmetic explains. For most graphics, physics homework and geometry, you will never notice it. It matters when you compare results with ==, which is covered below. If you want to understand why floats behave this way, see Python float type explained.

Area and circumference of a circle

The classic use. The area is pi times the radius squared, and the circumference is 2 times pi times the radius.

import math

radius = 5

area = math.pi * radius ** 2
circumference = 2 * math.pi * radius

print(area)
print(circumference)
print(round(area, 2))
print(round(circumference, 2))

Example output:

78.53981633974483
31.41592653589793
78.54
31.42

Use round(value, 2) or an f-string such as f"{area:.2f}" when you show the number to a person. Keep the full-precision value for further calculations and round only at the end. The ** operator is explained in Python exponent operator and pow().

As a reusable function

import math


def circle_area(radius: float) -> float:
    """Return the area of a circle with the given radius."""
    if radius < 0:
        raise ValueError("radius must not be negative")
    return math.pi * radius ** 2


print(circle_area(2))

Without the check, a radius of -3 would quietly return the same area as 3, because squaring removes the sign. A negative radius is almost always a bug upstream, so failing loudly is better. To go the other way and find a radius from an area, you need a square root, which is covered in Python square root examples.

Radians and degrees

Python's trigonometric functions take radians, not degrees. The documentation states that math.sin(x) returns "the sine of x radians". A half turn is pi radians, which is 180 degrees. Convert with math.radians() and math.degrees() instead of multiplying by pi yourself.

import math

print(math.degrees(math.pi))
print(math.radians(180))
print(math.sin(math.radians(30)))

Example output:

180.0
3.141592653589793
0.49999999999999994

The last line shows the rounding at work. The sine of 30 degrees is exactly 0.5 in mathematics, but the input was rounded when it became a float, so the result lands a hair below. A very common beginner error is calling math.sin(30) and expecting 0.5. That computes the sine of 30 radians, which is a different number entirely.

Why math.sin(math.pi) is not zero

The sine of pi is exactly 0, but math.pi is slightly different from pi, so Python returns a tiny leftover:

import math

print(math.sin(math.pi))
print(math.cos(math.radians(90)))

Example output:

1.2246467991473532e-16
6.123233995736766e-17

Both are about 10-16, which is zero for any practical purpose. The trouble starts if you test the result with == 0, which is False. The documentation provides math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) for this. It warns that comparing against 0.0 needs a positive abs_tol, because with the default settings isclose(x, 0) is False for any nonzero x:

import math

value = math.sin(math.pi)

print(value == 0)
print(math.isclose(value, 0))
print(math.isclose(value, 0, abs_tol=1e-9))

Example output:

False
False
True

Only the last line does what you want. Choose abs_tol to match the scale of your problem. For plain float comparison rules, the tutorial page on floating-point arithmetic gives the background, including why 0.1 + 0.1 + 0.1 == 0.3 is False.

math.tau: a full turn

Python also has math.tau, defined in the documentation as 6.283185… and "a circle constant equal to 2π, the ratio of a circle's circumference to its radius". Some formulas read more naturally with it: a full turn is math.tau radians, and the circumference is math.tau * radius.

import math

print(math.tau == 2 * math.pi)
print(math.tau)

Example output:

True
6.283185307179586

Nothing you can compute with tau is impossible with pi. Pick the one that matches the formula you are copying, so a reader can check the code against the source.

Common uses of pi in code

  • Circle and sphere geometry. Area, circumference, cylinder and cone volumes. For a sphere, the volume is 4 / 3 * math.pi * radius ** 3.
  • Angles for rotation. Turning an angle in degrees into radians before calling sin, cos or atan2.
  • Looping around a circle. Stepping an angle from 0 to 2 * math.pi to place points on a circle, for example when drawing or animating.
  • Statistics. The normal distribution formula contains math.sqrt(2 * math.pi).

Points around a circle, to show the loop pattern:

import math

points = 4
radius = 1

for step in range(points):
    angle = 2 * math.pi * step / points
    x = radius * math.cos(angle)
    y = radius * math.sin(angle)
    print(round(x, 3), round(y, 3))

Example output:

1.0 0.0
0.0 1.0
-1.0 0.0
-0.0 -1.0

The -0.0 values are real: they are tiny negative numbers rounded to three places, and floats keep the sign of zero. They compare equal to 0.0, so they only look odd when printed.

Can I get more digits of pi?

Not from math.pi. It is one float, so you get about 15 to 17 significant digits and no more. Formatting does not add accuracy: f"{math.pi:.30f}" prints 30 digits, but digits past the float's precision only show the binary value that is stored, not the true digits of pi. The floating-point tutorial shows the same effect for 0.1, whose exact stored value is 0.1000000000000000055511151231257827021181583404541015625. If you need exact decimal arithmetic for money-type values, the tutorial points to the decimal module, but that module does not ship a pi constant, so you would have to compute or supply the digits yourself.

Where does the numpy version fit?

If you already use numpy, it offers its own numpy.pi. Both are the same double-precision value, so results match. Importing numpy only for the constant is unnecessary. Use math.pi unless numpy is already in your script. For related numeric work with that library, see Python mean with statistics and numpy.

If it still fails

  • NameError: name 'pi' is not defined: add import math and write math.pi, or add from math import pi.
  • AttributeError: module 'math' has no attribute 'pi': a file named math.py in your project folder is shadowing the standard library module. Rename that file and delete its __pycache__ folder.
  • TypeError: 'float' object is not callable: pi is a value, not a function. Write math.pi, never math.pi().
  • A result that is off in the 16th digit, or a comparison that fails: this is float rounding, not a bug in math.pi. Use math.isclose and round for display.

Frequently asked questions

How do I get pi in Python?
Run import math, then use math.pi. It is a float constant equal to 3.141592653589793 when printed. It needs no installation because the math module is part of the standard library.
How many digits of pi does Python have?
math.pi is a 64-bit float, so it holds about 15 to 17 significant decimal digits. It prints as 3.141592653589793. The Python documentation describes it as pi 'to available precision'. For more digits you need a different tool, such as exact arithmetic with a series you implement yourself.
What is the difference between math.pi and math.tau?
math.tau is 2 times math.pi, about 6.283185. The Python documentation describes tau as the ratio of a circle's circumference to its radius. Use whichever makes your formula clearer; the results are the same.
Why is math.sin(math.pi) not exactly 0?
math.pi is a rounded approximation of the real pi, so the sine of it is a tiny nonzero number, about 1.2246e-16. Compare with math.isclose and an abs_tol, not with ==.

Sources