Search notes:

Oracle SQL MODEL clause example: Approximate PI with the Leibnitz formula

The Leibnitz formula for π is: π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - …
The following example uses the model clause to approximate pi. The iteration stops when the current iteration's approximated value for π is equal to four decimal places to the approximated value in the previous iteration.
create table tq84_approx_pi as
select
   iter,
   round(pi_approx,4) pi_approx
from
   dual 
model
   dimension by (0 as iter     )
   measures     (0 as pi_approx, 0 as div)
  rules
   iterate (10000000) until (
      round(pi_approx[iteration_number+1], 4) = round(pi_approx[iteration_number], 4)
   )
   (
      pi_approx[iteration_number+1] = pi_approx[iteration_number] + 4 /( (iteration_number  ) * 2 +1) * case when mod(iteration_number+1,2) = 1 then 1 else -1 end,
      div      [iteration_number+1] =                               4 /( (iteration_number  ) * 2 +1) * case when mod(iteration_number+1,2) = 1 then 1 else -1 end
   );

select * from tq84_approx_pi order by iter desc;

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1745357432, '13.59.147.113', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/databases/Oracle/SQL/select/model/examples/approximate-pi(55): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78