Toad World® Forums

OT: Happy Pi Day


#1

Happy 3/14! Here’s some code to cook your database’s CPU:

DECLARE
	prec	pls_integer := 1000000; 
	s	FLOAT(126) := 1;
	ns	FLOAT(126) := 2;
	pi	FLOAT(126) := 3;
BEGIN
	FOR k IN 1 .. prec
	LOOP
		pi := pi + (s * 4) / ( (ns*k) * (ns*k+1) * (ns*k+2) );
		s := -s;
	END LOOP;
	DBMS_OUTPUT.put_line('PI:		'||TO_CHAR(4*ATAN(1),'FM9.999999999999999999999999999999999999'));
	DBMS_OUTPUT.put_line('Calcd:	'||TO_CHAR(pi,           'FM9.999999999999999999999999999999999999'));
END;
/

It won’t get you to 31.4 trillion decimals of precision, but it’ll get close. Increasing the value of “prec” gets closer, but takes much longer for each successive digit.

Enjoy!
Rich

p.s. The above code, with “1000000” runs in about 1 second in Toad on my dev DB. Adding two zeros to the end of that value causes it to run for over 2 minutes.