Friday, March 14, 2025

pi.py day: "vibe coding" with AI

How good is AI for writing code?
Generating unlimited digits of "pi" is not an easy task.
So I prompted Sonnet 3.7 (on Claude, made by Anthropic) to do it.
And it did! See code below.
This is apparently now called "Vibe coding" :)


Pi Day is an annual celebration of the mathematical constant π (pi). Pi Day is observed on March 14 (the 3rd month) since 3, 1, and 4 are the first three significant figures of π

related:


this 9-lines JS code (link above) is much faster that AI generated code... interesting!
That is because BigInt is faster than "decimal".

Vibe coding - Wikipedia

Vibe coding is an AI-dependent computer programming practice where a person describes a problem in a few sentences as a prompt to a large language model (LLM) tuned for coding. The LLM generates software, freeing the programmer from having to write and debug the underlying code.[1][2][3] Vibe coding is claimed by its advocates to allow even amateur programmers to produce software without the extensive training and skills which coding previously needed.[4] The term was introduced by Andrej Karpathy in February 2025

We have used Python for this task.

That worked!

AI also explained advanced algorithm used (see below)

Then I asked to compare with Google's public API where millions of digits of Pi are available
url = f"https://api.pi.delivery/v1/pi?start={start_position}&numberOfDigits={digits_to_request}"
That worked also! No errors.

Next I asked to save timestamps every 100 digits generated to a CSV file
and generate chart.
By know, you know the result, right?

Interesting find: the more digits is requested to be calculated, 
the time for initial digits is increased too with this algorithm.
I.e. first 10000 digits takes 1 second when only this is requested.
When 20000 digits is calculated, first 10000 takes 2 seconds.
When 30000 digits is calculated, first 10000 takes about 3 seconds, etc.



Then we translated to JavaScript.
That worked also, but much slower.
Why?
Python "digits" package is in "native" (C) compiled code.
JavaScript "digits.js" module is a script, not native. So it is much slower, i.e. 10x

So you have it. 
AI can code, at least for "known problems" like Pi digits calculation.



The AI also explained the algorithm used:

"In the code I provided, I'm using the Chudnovsky algorithm to calculate π. This algorithm was developed by the Chudnovsky brothers (David and Gregory) in 1989 and is one of the most efficient methods for calculating π to high precision.

The algorithm is based on a rapidly converging series that adds approximately 14 decimal digits of π per iteration, making it much more efficient than older methods like the Bailey–Borwein–Plouffe formula or Machin's formula.

The Chudnovsky algorithm uses the following formula:

1/π = 12 ∑(k=0 to ∞) [(-1)^k × (6k)! × (545140134k + 13591409)] / [(3k)! × (k!)^3 × 640320^(3k+3/2)]

In the code, you can see this implemented with variables like C, M, L, X, K, and S, which track the various parts of the calculation as we compute terms in the series.

This algorithm is notable for being used in many record-setting calculations of π, including several computations of π to trillions of digits."




import time
import decimal
from decimal import Decimal

def calculate_pi(digits):
    """
    Calculate π using the Chudnovsky algorithm.
    This is one of the most efficient algorithms for calculating π.
    """
    decimal.getcontext().prec = digits + 10  # Extra digits for accuracy
   
    start_time = time.time()
   
    # Chudnovsky algorithm constants
    C = 426880 * Decimal(10005).sqrt()
    M = Decimal(1)
    L = Decimal(13591409)
    X = Decimal(1)
    K = Decimal(6)
    S = L
   
    for i in range(1, digits // 14 + 10):  # Each iteration gives ~14 digits
        M = M * (K**3 - 16*K) // (i**3)
        L += 545140134
        X *= -262537412640768000
        S += (M * L) / X
        K += 12
   
    pi_value = C / S
   
    # Format to the correct number of digits
    pi_str = str(pi_value)[:digits+2]  # +2 for "3."
   
    end_time = time.time()
    return pi_str, end_time - start_time

def main():
    """Main function to calculate π with user input."""
    results = []
   
    while True:
        try:
            digits = int(input("Enter the number of digits of π to calculate (0 to exit): "))
            if digits == 0:
                break
            if digits < 0:
                print("Please enter a positive number.")
                continue
           
            if digits > 1000:
                print("Warning: Large numbers of digits may take a long time to calculate.")
                confirm = input("Continue? (y/n): ").lower()
                if confirm != 'y':
                    continue
               
            print(f"\nCalculating π to {digits} digits...")
            pi_value, calculation_time = calculate_pi(digits)
           
            # Print the current result
            print(f"π = {pi_value}")
            print(f"Time taken: {calculation_time:.6f} seconds")
           
            # Store the result
            results.append((digits, pi_value, calculation_time))
           
            print("\n" + "="*50)
           
        except ValueError:
            print("Please enter a valid integer.")
        except Exception as e:
            print(f"An error occurred: {e}")
   
    # Print all results at the end
    if results:
        print("\nSummary of all calculations:")
        print("-" * 70)
        print(f"{'Digits':<10} {'Time (seconds)':<15} {'Value of π'}")
        print("-" * 70)
       
        for digits, pi_value, calculation_time in results:
            print(f"{digits:<10} {calculation_time:<15.6f} {pi_value}")

if __name__ == "__main__":
    print("π Calculator Program")
    print("=" * 30)
    main()
    print("\nThank you for using the π calculator!")








No comments: