2010-09-19 69 views
1
(def throws 10) 

(defn r-squared [x y] 
(+ (* (- 0.5 x) (- 0.5 x)) 
    (* (- 0.5 y) (- 0.5 y)))) 

(loop [hits 0] 
    (let [x (rand) 
     y (rand)] 
    ; still inside the let 
    (if (< (r-squared x y) 0.25) ;is it a hit or not? if not, try again 
     (recur (inc hits)) 
     (* 4 (/ hits throws))))) 

我得到了代碼工作和運行,直到if條件爲真。我該如何重寫它,以便將X作爲參數並運行X次?把clojure代碼放在一個循環中

我基本上想打電話給(r-squared 100),並得到多少點擊作爲返回值。

回答

0

我認爲這是你想要的,如果正確地延伸問題。

(defn test [n] 
    (loop [hits 0 n n] 
    (let [x (rand) 
      y (rand)] 
     (if (< n 0) 
      hits ;// you can put (* 4 (/ hits throws)) here 
      (if (< (r-squared x y) 0.25) 
       (recur (inc hits) (dec n)) 
       (recur hits (dec n))))))) 
+0

我怎麼及時把這個包來獲得exeuction時間? – peter 2010-09-19 22:56:02

+0

包裝你的電話及時測試。 '(時間(測試100))' – Rayne 2010-09-19 23:05:41

+0

代碼永遠不會改變n的值。這相當於海報初始代碼,對於任何大於0的n。 – 2010-09-20 09:52:34

0

沒有評估它,所以parn可能會有一點錯誤。

(def throws 10) 

(defn r-squared [x y] 
(+ (* (- 0.5 x) (- 0.5 x)) 
    (* (- 0.5 y) (- 0.5 y)))) 


(defn test-r-squared [n] 
    (loop [hits (int 0) n (int n)] 
    (let [x (rand) 
     y (rand)] 
    ; still inside the let 
    (if (< n 0) 
     (* 4 (/ hits throws)) 
     (if (< (r-squared x y) 0.25) ;is it a hit or not? if not, try again 
     (recur (inc hits) (dec n)) 
     (recur hits (dec n))))))) 
0
(defn r-squared [x y] 
(+ (* (- 0.5 x) (- 0.5 x)) 
    (* (- 0.5 y) (- 0.5 y)))) 

(defn hit[] 
    (let [x (rand) y (rand)] 
    (< (r-squared x y) 0.25))) 


(frequencies (for [i (range 1000)] (hit))) ; {true 787, false 213}