Visualizing the Prime Number Theorem with Python:A Comparison of \( \pi(x) \) and \( \frac{x}{\log x} \)

Here’s an example from Analytic Number Theory with a complete solution and visualization in $Python$.


πŸ“š Problem: Prime Number Theorem Approximation

The Prime Number Theorem (PNT) states that:

$$
\pi(x) \sim \frac{x}{\log x}
$$

Where:

  • $( \pi(x) )$ is the number of primes less than or equal to $( x )$.
  • $( \frac{x}{\log x} )$ approximates $( \pi(x) )$ for large values of $( x )$.

🎯 Goal:

  1. Calculate $( \pi(x) )$ for values up to $( x = 100,000 )$.
  2. Compare it with the approximation $( \frac{x}{\log x} )$.
  3. Visualize the results using a graph.

πŸ“ Step 1: Define and Calculate Functions

  • pi(x): Count primes less than or equal to $( x )$.
  • Approximation: Use $( \frac{x}{\log x} )$.

🧩 Step 2: Python Code Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Import required libraries
import numpy as np
import matplotlib.pyplot as plt
from sympy import primepi
from math import log

# Define the range and step size
x_values = np.linspace(10, 100000, 200) # Range from 10 to 100,000 with 200 points

# Calculate prime counting function pi(x)
pi_values = [primepi(int(x)) for x in x_values]

# Calculate the Prime Number Theorem (PNT) approximation
pnt_approx = [x / log(x) for x in x_values]

# Plot the results
plt.figure(figsize=(10, 6))
plt.plot(x_values, pi_values, label=r'$\pi(x)$ (Prime Count)', color='blue')
plt.plot(x_values, pnt_approx, label=r'$\frac{x}{\log x}$ (PNT Approximation)', linestyle='--', color='red')

# Add title and labels
plt.title("Prime Number Theorem: $\pi(x)$ vs. $\dfrac{x}{\log x}$", fontsize=14)
plt.xlabel("x", fontsize=12)
plt.ylabel("Value", fontsize=12)
plt.legend()
plt.grid(True)

# Show the plot
plt.show()

πŸ“Š Step 3: Explanation and Visualization

βœ… Explanation:

  1. pi(x): Using primepi() from sympy to compute the exact number of primes up to $( x )$.
  2. PNT Approximation: Using the formula $( \frac{x}{\log x} )$.
  3. Graph:
    • Blue line: Exact prime counting function.
    • Red dashed line: PNT approximation.


πŸ“ˆ Step 4: Interpretation of Results

  • The graph shows that the approximation $( \frac{x}{\log x} )$ becomes increasingly accurate as $( x )$ increases.
  • For smaller values of $( x )$, there is a noticeable gap, but for large $( x )$, the approximation closely tracks $( \pi(x) )$.

πŸ“’ Insights:

  • The Prime Number Theorem provides a remarkably simple yet powerful approximation for the distribution of prime numbers.
  • This visualization helps highlight how the error margin decreases with larger $( x )$.