Sunday, October 12, 2008

Calculating pi in LOLCODE

Magnus Hagander asked me for a simple function to return a number using PL/LOLCODE. Here's a pi calculator, based on a post by Grzegorz Jaśkiewicz on the PostgreSQL GENERAL mailing list showing how to find pi using PostgreSQL's new recursive query feature:

create or replace function lol_pi() returns float immutable language pllolcode as $$
HAI

I HAS A PIADD ITZ 0.0
I HAS A PISUB ITZ 0.0
I HAS A ITR ITZ 0
I HAS A ITRZ ITZ 20000
I HAS A T1
I HAS A T2

IM IN YR LOOP

T1 R QUOSHUNT OF 4.0 AN SUM OF 3.0 AN ITR
T2 R QUOSHUNT OF 4.0 AN SUM OF 5.0 AN ITR
PISUB R SUM OF PISUB AN T1
PIADD R SUM OF PIADD AN T2
ITR R SUM OF ITR AN 4.0
BOTH SAEM ITR AN BIGGR OF ITR AN ITRZ, O RLY?

YA RLY, GTFO

OIC

IM OUTTA YR LOOP
FOUND YR SUM OF 4.0 AN DIFF OF PIADD AN PISUB

KTHXBYE
$$;

select lol_pi();

UPDATE: Fixed indenting to make this look nicer, and credited the mailing list post
UPDATE PART 2: Note that this particular function doesn't use anything special about PL/LOLCODE, and AFAICS should run just fine in any LOLCODE interpreter.
UPDATE PART 3: Note also that there are better facilities for loops in LOLCODE, but PL/LOLCODE doesn't implement them yet, which is why I've got to track the counter explicitly, and explicitly GTFO when it hits ITRZ.
UPDATE PART 3: Some investigation has revealed that this method of calculating pi is called a Gregory-Leibniz series

No comments: