Skip to content

Software101DotNet/Pi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 

Repository files navigation


Calculate Pi

The code implements the calculation of a numerical approximation of π using the Riemann Sum method with the midpoint rule.

Report Bug · Request Feature

About The Implementation

There are two implementations. C++ and C#. They are intended to be functionally equivalent, although the C++ implementation executes in approximately 1200 milliseconds on an Apple M4 processor, whereas the C# implementation executes in approximately 2700 milliseconds.

The outline of the algorithm is as follows:

Sets the number of iterations to the maximum integer value for precision. N = int.MaxValue (2,147,483,647)

Loop (i = 0 to N-1) for each iteration:

t = (i + 0.5) / N calculates the midpoint of each subinterval 4.0 / (1.0 + t * t) evaluates the function f(t) = 4/(1+t²) at that midpoint tempPi += ... accumulates the sum pi = tempPi / N: Divides the sum by N to compute the average, which approximates the integral ∫₀¹ 4/(1+t²) dt = π

This is based on the mathematical identity that the arctangent integral equals π/4, so multiplying by 4 gives π. The more iterations (larger N), the more accurate the approximation. With two billion iterations, the resulting calculation will converge to a value of π that is accurate to 12 decimal places.

Building an executable from the source code

On macOS or Windows, open a terminal. Build the C# version using the command line:

dotnet build ./PiCSharp/Pi.csproj --configuration Release

Build the C++ version using the command line:

g++ -O3 -DNDEBUG -flto -std=c++20 ./PiCpp/main.cpp -o Pi

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published