import Color exposing (..) import Graphics.Collage exposing (..) import Graphics.Element exposing (..) import Random import List import Text -- Change the number of random points to approximate the -- area of the square and of the circle. -- Generally, but not always, more points gives a better answer. -- WARNING: Don't go over 100000 numPoints = 900 -- This describes the type of random numbers we want: -- a List of Floats (numbers with fractions) floatListGen : Random.Generator (List Float) floatListGen = Random.list numPoints (Random.float (-radius) radius) -- We use two such lists of random numbers to create -- a single list of (x,y) points. -- fst takes the first of a pair, because Random.generate -- returns both the random list, and the next seed, -- so we can get different random numbers the next time -- Random numbers are calculated by repeating a complicated -- calculation to produce a sequence of numbers whose pattern -- is so complicated it seems random, but to start it off we -- need to give it an initial number, which is the "seed". xyList = List.map2 (,) (fst <| Random.generate floatListGen (Random.initialSeed 12432412)) (fst <| Random.generate floatListGen (Random.initialSeed 327432)) radius = 200 r2 = radius^2 -- run an (x,y) into a filled circle at that location point (x,y) = filled (if x^2 + y^2 > r2 then purple else pink) (circle 2) |> move (x,y) counts c list = case list of ((x,y)::rest) -> if x^2 + y^2 <= r2 then counts (c+1) rest else counts (c ) rest [] -> c total = toFloat numPoints inCircle = counts 0 xyList main : Element main = collage 500 500 <| [ outlined (solid plum) (square (2*radius)) -- Uncomment this to see the circle! -- , filled peach (circle radius) ] ++ ( List.map point xyList ) ++ [ " 4 * " ++ (toString inCircle) ++ " / " ++ (toString total) ++ " = " ++ (toString (4 * inCircle / total)) |> Text.fromString |> Text.style plumyStyle |> text |> move (0,-210) ] pink = hsl (degrees 312) 0.95 0.8 purple = hsl (degrees 265) 0.95 0.8 peach = hsl (degrees 36) 0.95 0.87 plum = hsl (degrees 216) 0.8 0.43 plumyStyle = { typeface = [ "Times New Roman", "serif" ] , height = Just 20 , color = plum , bold = True , italic = False , line = Nothing }