2010-09-19 29 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}