Back

random (clj)

(source)

function

(random)
Returns a positive double between 0.0 and 1.0, chosen pseudorandomly with approximately random distribution. See: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random--

Examples

lspector/Clojush
(ns clojush.instructions.random-instructions
  (:use [clojush pushstate random globals translate])
  (:require [clojure.math.numeric-tower :as math]))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; random instructions

(define-registered
  boolean_rand
  ^{:stack-types [:boolean :random]}
  (fn [state]
    (push-item (lrand-nth [true false]) :boolean state)))

(define-registered
  integer_rand
  ^{:stack-types [:integer :random]}
  (fn [state]
    (push-item (+' (lrand-int (+ 1 (- max-random-integer min-random-integer)))
                   min-random-integer)
               :integer
               state)))

(define-registered
  float_rand
  ^{:stack-types [:float :random]}
  (fn [state]
    (push-item (+' (lrand (- max-random-float min-random-float))
                   min-random-float)
               :float
               state)))

(define-registered
  code_rand
  ^{:stack-types [:code :integer :random]}
  (fn [state]
    (if (not (empty? (:integer state)))
      (if (empty? @global-atom-generators)
        (binding [*out* *err*]
	         (println "code_rand: global-atom-generators is empty.")
	         state)
        (push-item (random-push-code (max 1
                                          (math/abs (mod (stack-ref :integer 0 state)
                                                         max-points-in-random-expressions)))
                                     @global-atom-generators)
                   :code
                   (pop-item :integer state)))
      state)))

(define-registered
  code_rand_atom
  ^{:stack-types [:code :random]}
  (fn [state]
    (if (empty? @global-atom-generators)
      (binding [*out* *err*]
        (println "code_rand_atom: global-atom-generators is empty.")
        state)
      (push-item (random-atom @global-atom-generators)
                 :code
                 state))))

(define-registered
  string_rand
  ^{:stack-types [:string :random]}
  (fn [state]
    (push-item
      (apply str (repeatedly
                   (+' min-random-string-length
                       (lrand-int (- max-random-string-length
                                     min-random-string-length)))
                   (fn [] (lrand-nth (vec (concat ["\n" "\t"] 
                                                  (map (comp str char) 
                                                       (range 32 127))))))))
      :string
      state)))

(define-registered
  char_rand
  ^{:stack-types [:char :random]}
  (fn [state]
    (push-item (lrand-nth (vec (concat [\newline \tab] 
                                       (map char (range 32 127)))))
               :char
               state)))
puppetlabs/puppetdb
(ns puppetlabs.puppetdb.utils.string_formatter-test
  (:require [clojure.test :refer :all]
            [clojure.string :as string]
            [clojure.math.combinatorics :refer [selections]]
            [puppetlabs.puppetdb.utils.string-formatter
             :refer [dash->underscore-keys
                     pprint-json-parse-exception
                     re-quote
                     underscore->dash-keys]]
            [clojure.test.check.generators :as gen]
            [clojure.test.check.properties :as prop]
            [clojure.test.check.clojure-test :as cct]))

(deftest test-pprint-json-parse-exception
  (let [query "[\"from\", \"nodes\"] lk"
        error-message (str "Unrecognized token random: was expecting "
                           "(JSON String, Number, Array, Object or token null, true or false)\n"
                           " at [String.Reader line: 1, column: 21]")
        expected-message (str "Json parse error at line 1, column 21:\n\n"
                              "[\"from\", \"nodes\"] lk\n"
                              "                   ^\n\n"
                              "Unrecognized token random: was expecting "
                              "(JSON String, Number, Array, Object or token null, true or false)")
        mock-exception (ex-info error-message {})]
    (is (= expected-message (pprint-json-parse-exception  mock-exception query)))))
Vaguery/klapaucius
(ns push.type.module.random-scalars
  (:require [push.instructions.dsl      :as d]
            [push.instructions.core     :as i]
            [clojure.math.numeric-tower :as n]
            [push.type.core             :as t]
            ))

(def integer-uniform
  (i/build-instruction
    integer-uniform
    "`:integer-uniform` pops the top `:scalar` value, and pushes a uniform random integer (typecase from a uniform number on the range `[0.0, :arg)`). If the scalar is negative, a negative result is returned; if the argument is out of bounds (larger than Long/MAX_VALUE), an `:error` is pushed instead of a value."

(def float-uniform
  (i/build-instruction
    float-uniform
    "`:float-uniform` pops the top `:scalar` value, and pushes a random double uniformly sampled from the range [0,:f). If the float is negative, a negative result is returned."

(def boolean-faircoin
  (i/build-instruction
    boolean-faircoin
    "`:boolean-faircoin` pushes a random `:boolean` value, with equal probability `true` or `false`."


(def random-scalars-module
  ( ->  (t/make-module  :random-scalars
                        :attributes #{:numeric :random})
yetanalytics/datasim
(ns com.yetanalytics.datasim.util.random-test
  (:require [clojure.test :refer [deftest testing is]]
            [clojure.math :as math]
            [clojure.spec.test.alpha :as stest]
            [com.yetanalytics.datasim.util.random :as r]))

(deftest random-functions-test
  (testing "Generative tests"
    (let [results (stest/check
                   `#{r/rng
                      r/seed-rng
                      r/rand
                      r/rand-int
                      r/rand-unbound-int
                      r/rand-gaussian
                      r/rand-boolean
                      r/rand-exp
                      r/rand-uuid
                      r/rand-nth
                      r/shuffle
                      r/random-sample
                      r/choose
                      r/choose-map})
          {:keys [total
                  check-passed]} (stest/summarize-results results)]
      (is (= total check-passed)))))

(deftest choose-test
  (testing "choose function: equal weights"
    (test-equal-choose {})
    (test-equal-choose {:unrelated-key-1 0.2 :unrelated-key 0.8})
    (test-equal-choose {:foo 0.5 :baz 0.5})
    (test-equal-choose {:foo 0.0 :bar 0.0 :baz 0.0 :qux 0.0})
    (test-equal-choose {:foo 0.2 :bar 0.2 :baz 0.2 :qux 0.2})
    (test-equal-choose {:foo 0.8 :bar 0.8 :baz 0.8 :qux 0.8})
    (test-equal-choose {:foo 1.0 :bar 1.0 :baz 1.0 :qux 1.0}))
  (testing "choose function: only one non-zero weight"
    (let [weights   {:foo 0 :bar 0 :baz 1 :qux 0}
          the-rng   (r/rng)
          choose-fn (fn [] (r/choose the-rng weights choose-coll))
          results   (repeatedly choose-total choose-fn)
          freq-map  (frequencies results)]
      (is (= choose-total (:baz freq-map)))
      (is (nil? (:foo freq-map)))
      (is (nil? (:bar freq-map)))
      (is (nil? (:qux freq-map)))))
  ;; The probabilities are derived from integrating over the area defined
  ;; by the joint uniform distributions where (< x2 (max x1 t2)), where
  ;; x1 and x2 are the independent (but not identical!) random variables
  ;; and t1 and t2 are the upper bounds of the uniform distributions.
  ;; In Clojure pseudocode:
  ;; (-> (/ 1 (* t1 t2))
  ;;     (integrate 0 (max x1 t2) dx2)
  ;;     (integrate 0 t1 dx1))
  ;; = (- 1 (/ t2 (* 2 t1))
  (testing "choose function: two different non-zero weights"
    (let [weights   {:foo 0 :bar 0 :baz 1 :qux 0.4}
          prob-1    0.8
          prob-2    0.2
          mean-1    (* choose-total prob-1)
          mean-2    (* choose-total prob-2)
          sd        (math/sqrt (* choose-total prob-1 prob-2))
          lo-1      (- mean-1 (* sd-limit sd))
          lo-2      (- mean-2 (* sd-limit sd))
          hi-1      (+ mean-1 (* sd-limit sd))
          hi-2      (+ mean-2 (* sd-limit sd))
          the-rng   (r/rng)
          choose-fn (fn [] (r/choose the-rng weights choose-coll))
          results   (repeatedly choose-total choose-fn)
          freq-map  (frequencies results)]
      (is (< lo-1 (:baz freq-map) hi-1))
      (is (< lo-2 (:qux freq-map) hi-2))
      (is (nil? (:foo freq-map)))
      (is (nil? (:bar freq-map)))))
  (testing "choose-map function works just like choose"
    (let [weights       {:foo 0.2 :bar 0.4 :baz 0.6 :qux 0.8}
          seed          (r/rand-unbound-int (r/rng))
          rng-1         (r/seed-rng seed)
          rng-2         (r/seed-rng seed)
          choose-fn     (fn [] (r/choose rng-1 weights choose-coll))
          choose-map-fn (fn [] (r/choose-map rng-2 weights choose-map))
          results-1     (repeatedly choose-total choose-fn)
          results-2     (repeatedly choose-total choose-map-fn)
          freq-map-1    (frequencies results-1)
          freq-map-2    (frequencies results-2)]
      (is (= (:foo freq-map-1)
             (:FOO freq-map-2)))
      (is (= (:bar freq-map-1)
             (:BAR freq-map-2)))
      (is (= (:baz freq-map-1)
             (:BAZ freq-map-2)))
      (is (= (:qux freq-map-1)
             (:QUX freq-map-2))))))
wedesoft/sfsim25
(ns sfsim25.t-bluenoise
    (:require [clojure.math :refer (exp)]
              [midje.sweet :refer :all]
              [malli.instrument :as mi]
              [malli.dev.pretty :as pretty]
              [fastmath.vector :refer (vec3)]
              [sfsim25.conftest :refer (record-image is-image)]
              [sfsim25.bluenoise :refer :all]
              [sfsim25.render :refer :all]
              [sfsim25.shaders :as shaders])
    (:import [org.lwjgl.glfw GLFW]))

(facts "Pick n random values from array"
       (pick-n [0 1 2 3] 2 identity) => [0 1]
       (pick-n [0 1 2 3] 2 reverse) => [3 2]
       (count (pick-n [0 1 2 3] 2)) => 2)