Jump to content

rnd-split-number


Recommended Posts


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;how to split randomly a number into "n-parts"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defun rnd-split-number (n &key (total-sum 1.0))
  (let ((values))
    (setq values (loop repeat (- n 1)
                   with val-a = total-sum
                   with val-b
                   collect (setq val-b (random val-a))
                   do (setq val-a (- val-a val-b))))
    (append values (list (- total-sum (sum values))))))


;; examples
(rnd-split-number 5 :total-sum 1.8)

=> (0.26645982 1.47964 0.014375878 0.014122969 0.025401235)

(rnd-split-number 3 :total-sum 9.8)

=> (5.1533704 1.7459779 2.900652)

 

Link to comment
Share on other sites

With SEED:

(defun rnd-division (n &key (sum 1.0) seed)
  (do-verbose ("rnd-division")
    (rnd-seed seed)
    (let ((values
           (loop repeat (- n 1)
             with a = sum
             with b
             collect (setf b (random* a :seed (seed)))
             do (setf a (- a b)))))
      (append values (list (- sum (sum values)))))))

(rnd-division 5 :seed 5)
=> (0.0052785673 0.09165209 0.06036401 0.65849 0.1842153)

(rnd-division 3 :sum 9.8 :seed 87)
=> (3.9023237 0.8761092 5.0215673)

 

To add seed to the function use RANDOM* OM function.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

Terms of Use Privacy Policy