You can use the following series to calculate pi:
4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
I
decided to try this out using PL/SQL. The example I created is shown
below. It works OK but the series converges very slowly so you have to
work out several million terms just to get pi accurate to 6 decimal
places:
SQL> declare
2 pi number := 0;
3 numerator number := 4;
4 denominator number := 1;
5 dp number := 0;
6 pi1 number;
7 pi2 number;
8 counter number := 0;
9 finished boolean := false;
10 begin
11 while not finished
12 loop
13 pi := pi + (numerator / denominator);
14 pi1 := round (pi,dp);
15 denominator := denominator + 2;
16 pi := pi - (numerator / denominator);
17 pi2 := round (pi,dp);
18 denominator := denominator + 2;
19 counter := counter + 1;
20 if pi1 = pi2 then
21 dbms_output.put_line ('Counter = '||counter);
22 if dp = 1 then
23 dbms_output.put_line
24 ('Accurate to 1 decimal place:');
25 else
26 dbms_output.put_line
27 ('Accurate to '||dp||' decimal places:');
28 end if;
29 dbms_output.put_line ('Pi = '||pi1);
30 dbms_output.put_line ('**********');
31 dp := dp + 1;
32 if dp > 6 then
33 finished := true;
34 end if;
35 end if;
36 end loop;
37 end;
38 /
Counter = 2
Accurate to 0 decimal places:
Pi = 3
**********
Counter = 60
Accurate to 1 decimal place:
Pi = 3.1
**********
Counter = 148
Accurate to 2 decimal places:
Pi = 3.14
**********
Counter = 5397
Accurate to 3 decimal places:
Pi = 3.142
**********
Counter = 11723
Accurate to 4 decimal places:
Pi = 3.1416
**********
Counter = 213092
Accurate to 5 decimal places:
Pi = 3.14159
**********
Counter = 3255425
Accurate to 6 decimal places:
Pi = 3.141593
**********
PL/SQL procedure successfully completed.
Elapsed: 00:00:34.53
SQL>
No comments:
Post a Comment