Saturday 20 March 2021

Pi or π Represented as a Fraction

You can use pi (or π) to calculate:

(1) The circumference of a circle.

(2) The area of a circle.

(3) The volume of a sphere.

But what is the value of pi?

Pi is irrational so you cannot represent it exactly as a fraction. At school we used 3.14 and 22/7 as rough estimates. There is also a better approximation, which uses a fraction with a 3 figure numerator and denominator but I could not remember it. I looked up pi to several decimal places then worked it out by trial and error with the PL/SQL code below:

SQL> @pi

SQL> set serveroutput on

SQL> declare

 2  top number;

 3  bottom number;

 4  pi constant number := 3.141592654;

 5  ratio number;

 6  difference number;

 7  save_difference number := 1;

 8  save_top number;

 9  save_bottom number;

 10  save_ratio number;

 11 begin

 12  for top in 1..999 loop

 13   for bottom in 1..999 loop

 14    ratio := top/bottom;

 15    difference := abs(pi-ratio);

 16    if difference < save_difference then

 17     save_difference := difference;

 18     save_top := top;

 19     save_bottom := bottom;

 20     save_ratio := ratio;

 21    end if;

 22   end loop;

 23  end loop;

 24  dbms_output.put_line('Top: '||save_top);

 25  dbms_output.put_line('Bottom: '||save_bottom);

 26  dbms_output.put_line('Ratio: '||save_ratio);

 27 end;

 28 /

Top: 355

Bottom: 113

Ratio: 3.14159292035398230088495575221238938053 

PL/SQL procedure successfully completed. 

SQL>  

So there you have it. A better approximation to pi is 355/113, which is accurate to 6 decimal places i.e. 3.141593.

No comments:

Post a Comment