How To Compute Fibonacci Extensions in Ruby?

by buster.gaylord , in category: General Help , 4 months ago

How To Compute Fibonacci Extensions in Ruby?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by tina , 4 months ago

@buster.gaylord 

To compute Fibonacci extensions in Ruby, you can write a simple function that generates the Fibonacci sequence up to a certain number of terms and then calculates the Fibonacci extensions based on those numbers. Here's a step-by-step guide to writing a Ruby program to compute Fibonacci extensions:


Step 1: Define a function to generate the Fibonacci sequence

1
2
3
4
5
6
7
def fibonacci(n)
  fib = [0, 1]
  (2..n).each do |i|
    fib[i] = fib[i - 1] + fib[i - 2]
  end
  return fib
end


Step 2: Define a function to calculate Fibonacci extensions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def fibonacci_extensions(n)
  fib = fibonacci(n)
  
  retracement_levels = []
  extension_levels = []
  
  # Calculate retracement levels
  retracement_levels << fib[n]
  retracement_levels << fib[n] - ((fib[n] - fib[n-1]) * 0.236)
  retracement_levels << fib[n] - ((fib[n] - fib[n-1]) * 0.382)
  retracement_levels << fib[n] - ((fib[n] - fib[n-1]) * 0.618)
  
  # Calculate extension levels
  extension_levels << fib[n] + ((fib[n] - fib[n-1]) * 2)
  extension_levels << fib[n] + ((fib[n] - fib[n-1]) * 3)
  extension_levels << fib[n] + ((fib[n] - fib[n-1]) * 4)
  
  return retracement_levels, extension_levels
end


Step 3: Test the function with a sample input

1
2
3
4
5
n = 10
retracement_levels, extension_levels = fibonacci_extensions(n)

puts "Retracement levels: #{retracement_levels}"
puts "Extension levels: #{extension_levels}"


This code will calculate the Fibonacci extensions for the Fibonacci sequence up to the 10th term. You can modify the value of 'n' to calculate extensions for a different number of terms.