Monday, August 15, 2011

Numeral systems

Here is a function that can be used to evaluate any numeral:

(defn evaluate-numeral
  [numerals radix]

  (apply +
  (map-indexed
   (fn [i v]
     (* v (Math/pow radix (- (dec (count numerals)) i))))
   numerals)))

(= (evaluate-numeral '(1 0 1 0 1) 2)
   21)

You can also evaluate the amount of digits needed for a number in any numeral system:

(defn digits-in-number
  [num radix]

  (inc (Math/floor (/ (Math/log num) (Math/log radix)))))

(= (digits-in-number 255 2)
   8)

No comments:

Post a Comment