-
-
Save floehopper/214172 to your computer and use it in GitHub Desktop.
how do you test algorithms?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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