This file contains 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
def fib(n): | |
""" old fib exponential complexity ? """ | |
if n == 0 or n == 1: | |
return 1 | |
else: | |
return fib(n - 1) + fib(n - 2) | |
#Julia | |
fib(n::Integer) = return(n > 1 ? (fib(n-1) + fib(n-2)) : one(n)) | |
# ::Integer defines a function for integers only | |
# Julia's multiple dispatch lets you define methods for different | |
# types matching against all unnamed types in the method definition | |
# As suggested by Steven Johnson, using one(n) rather than 1 | |
# ensures that the result has the same type as n |
I also started learning a bit about Julia's Glamor of Graphics style plotting module, Gadfly. Here's todays experiment:
Still waiting for Python to finish ... perhaps after dinner ... 1 hour 10 minutes and 5 seconds. So Julia is 39 times faster than Python calculating the fib.
There is a typo in your Julia code: the function is called "fib2" but it calls "fib".
ReplyDeleteAlso, it would be better to do:
ReplyDeletefib(n) = return(n > 1 ? (fib(n-1) + fib(n-2)) : one(n))
where you use one(n) to ensure that the result has the same type as n.
Correct about the typo -- too many experiments leaving names lying around.
ReplyDeleteI like the type definition, thanks, and have amended it. I should probably limit it to integers as well. I'm currently struggling with scopes in memoization so I'll probably come back and improve it. No, it was easy. Done.