Skip to content

Instantly share code, notes, and snippets.

@floehopper
Forked from technoweenie/gist:213780
Created October 20, 2009 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save floehopper/214172 to your computer and use it in GitHub Desktop.
Save floehopper/214172 to your computer and use it in GitHub Desktop.
how do you test algorithms?
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment