I've been told, and I believe, that Clojure is faster than Python. Why does this Python code run faster than this seemingly equivalent Clojure code? Is Python doing some optimizations at compile time?
def find_fifty(n,memory=1,count=0):
if memory < 0.5:
return count
else:
return find_fifty(n,memory*(1 - count/n),count+1)
find_fifty(100000)
(defn fifty
([n] (fifty n 1 0))
([n memory count]
(if (< memory 0.5)
count
(recur n
(* memory (- 1 (/ count n)))
(inc count)))))
(fifty 100000)
It feels like the time complexity for Clojure is higher than for Python. The Python function can receive an input many times higher than the Clojure function before it has a significant increase in runtime.
Update - Clojure Fix
(defn fifty
([n] (fifty (float n) 1 0))
([n memory count]
(if (< memory 0.5)
count
(recur n
(* memory (- 1 (/ count n)))
(inc count)))))
(fifty 10000000)
As was answered, Clojure was keeping values as very large rational numbers. Converting it to a float simplifies the operations being done, thus decreasing the runtime.