Skip to content

Instantly share code, notes, and snippets.

@jimmckeeth
Last active April 13, 2023 18:50
Show Gist options
  • Save jimmckeeth/88d76a4ecee150e6cdcdf200b5c473a1 to your computer and use it in GitHub Desktop.
Save jimmckeeth/88d76a4ecee150e6cdcdf200b5c473a1 to your computer and use it in GitHub Desktop.
Pi Day 2023 with Delphi
// I created an updated blog post with new code, more accuracy, and digits:
// https://blogs.embarcadero.com/getting-big-with-pi-in-delphi/
unit PiDay2023;
interface
uses
Velthuis.BigIntegers,
Velthuis.BigDecimals;
// Use your favorite fork of https://github.com/TurboPack/RudysBigNumbers
function LeibnizPi(const Iterations: NativeUInt): Extended;
function NilkanthaPi(const Iterations: NativeUInt): Extended;
function BaileyBorweinPlouffePi(const Digits: NativeUInt): Extended;
function BigBaileyBorweinPlouffePi(const Digits: NativeUInt): BigDecimal;
implementation
uses
Math;
function LeibnizPi(const Iterations: NativeUInt): Extended;
begin
Result := 0;
var k: Extended := 1;
for var I := 0 to Iterations do
begin
if odd(I) then
Result := Result - 4 / k
else
Result := Result + 4 / k;
k := k + 2;
end;
end;
function NilkanthaPi(const Iterations: NativeUInt): Extended;
begin
Result := 3;
var n: Extended := 2;
var sign := 1;
for var I := 0 to Iterations do
begin
Result := Result + sign * (4 / (n * (n + 1) * (n + 2)));
sign := sign * -1;
n := n + 2;
end;
end;
function BaileyBorweinPlouffePi(const Digits: NativeUInt): Extended;
begin
Result := 0;
for var I := 0 to Digits do
begin
Result := Result + 1 / power(16, I) *
((4 / (8 * I + 1)) - (2 / (8 * I + 4)) - (1 / (8 * I + 5)) -
(1 / (8 * I + 6)));
end;
end;
function BigBaileyBorweinPlouffePi(const Digits: NativeUInt): BigDecimal;
begin
const sixteen = BigDecimal.Create(16);
Result := BigDecimal.Zero;
Result.DefaultPrecision := Digits;
for var I := 0 to Digits do
begin
var term1 := BigDecimal.Create((4 / (8 * I + 1)) - (2 / (8 * I + 4)) -
(1 / (8 * I + 5)) - (1 / (8 * I + 6)));
var term2 := BigDecimal.Divide(1, sixteen.IntPower(I, Result.DefaultPrecision), Result.DefaultPrecision);
Result := Result + BigDecimal.Multiply(term1, term2);
end;
end;
end.
@jimmckeeth
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment