How To Calculate Fibonacci Extensions using SQL?

by oda.tromp , in category: Technology , 2 months ago

How To Calculate Fibonacci Extensions using SQL?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by bailey_conroy , 2 months ago

@oda.tromp 

To calculate Fibonacci extensions using SQL, you will first need a table with the Fibonacci sequence. You can create this table using a common table expression (CTE) or by populating a table with the Fibonacci numbers up to a certain point.


Here is an example of how you can calculate Fibonacci extensions in SQL:

  1. Create a table with the Fibonacci sequence:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
WITH RECURSIVE Fibonacci AS (
  SELECT 0 AS n, 0 AS f
  UNION ALL
  SELECT 
    n + 1,
    CASE 
      WHEN n = 0 THEN 1 
      WHEN n = 1 THEN 1
      ELSE f + LAG(f, 1) OVER (ORDER BY n)
    END
  FROM Fibonacci
  WHERE n < 10 -- Change this to the desired number of Fibonacci numbers
)
SELECT *
FROM Fibonacci;


  1. Calculate the Fibonacci extensions using the Fibonacci numbers from the table:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
WITH Fibonacci AS (
  SELECT 0 AS n, 0 AS f
  UNION ALL
  SELECT 
    n + 1,
    CASE 
      WHEN n = 0 THEN 1 
      WHEN n = 1 THEN 1
      ELSE f + LAG(f, 1) OVER (ORDER BY n)
    END
  FROM Fibonacci
  WHERE n < 10 -- Change this to the desired number of Fibonacci numbers
),
Extensions AS (
  SELECT
    f1.f AS fib1,
    LAG(f2.f, 1) OVER (ORDER BY f2.n) AS fib2,
    LAG(f2.f, 2) OVER (ORDER BY f2.n) AS fib3,
    LAG(f2.f, 3) OVER (ORDER BY f2.n) AS fib4
  FROM Fibonacci f1
  CROSS JOIN Fibonacci f2
)
SELECT 
  fib1,
  fib1 + (fib1 - fib2) AS extension1,
  fib1 + (fib1 - fib3) AS extension2,
  fib1 + (fib1 - fib4) AS extension3
FROM Extensions;


In this example, the Fibonacci CTE generates the Fibonacci numbers up to 10, and the Extensions CTE calculates the first three Fibonacci extensions for each Fibonacci number. You can adjust the number of Fibonacci numbers generated and the number of extensions calculated by changing the values in the WHERE clause of the Fibonacci CTE and the LAG functions in the Extensions CTE.