floehopper (owner)

Revisions

gist: 214172 Download_button fork
public
Description:
how do you test algorithms?
Public Clone URL: git://gist.github.com/214172.git
Embed All Files: show embed
Ruby #
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# how do you test algorithms?
 
class Pythagoream < Struct.new(:a, :b)
  def result
    a**2 + b**2
  end
end
 
# I prefer to "invert" the algorithm somehow
# or calculate the expected result another way.
# The idea is to give me a "double-entry book-keeping" benefit :-
# f(x) should equal g(x), where g(x) is an alternative implementation of f(x)
 
def test_pythagoream
  opposite = 3.to_f
  adjacent = 4.to_f
  theta = Math.atan(opposite/adjacent)
  expected = adjacent / Math.cos(theta)
  assert_in_delta expected, Pythagoream.new(opposite, adjacent).result, 0.01
end
 
# Otherwise I think using explicit expected results
# is better than duplicating the algorithm in the test :-
 
def test_pythagoream
  assert_equal 25, Pythagoream.new(3, 4).result
end
 
# Here's a nicer example of where "inverting" the algorithm is useful :-
# f`(f(x)) should equal x, where f`(x) is the inverse of f(x)
 
class SquareRooter < Struct.new(:x)
  def result
    Math.sqrt(x)
  end
end
 
def test_square_rooter
  root = 5.0
  square = 5.0 ** 2
  assert_in_delta root, SquareRooter.new(square).result, 0.01
end