Module: Algorithmable::Cups::RootCubeIssue

Defined in:
lib/algorithmable/cups/root_cube_issue.rb

Constant Summary collapse

ACCURACY =

What is the fastest way to compute cube root?

0.0001

Class Method Summary collapse

Class Method Details

.binary_search(num, accuracy = ACCURACY) ⇒ Object


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/algorithmable/cups/root_cube_issue.rb', line 8

def self.binary_search(num, accuracy = ACCURACY)
  low = 0
  high = num
  mid = 0

  loop do
    mid = (low + high) / 2.0
    cube = mid * mid * mid
    break if (cube - num).abs <= accuracy
    if cube > num
      high = mid
    else
      low = mid
    end
  end
  mid
end

.newton_approximation(num, accuracy = ACCURACY) ⇒ Object


26
27
28
29
30
31
32
33
34
35
36
# File 'lib/algorithmable/cups/root_cube_issue.rb', line 26

def self.newton_approximation(num, accuracy = ACCURACY)
  x = 1
  n = 10
  loop do
    0.upto(n).each do
      x = (2 * x + num / (x * x)) / 3.0
    end
    break if ((x * x * x) - num).abs < accuracy
  end
  x
end