0

How do I get the exact answer instead of just the number / count

I can get the average of a list of numbers, but it will only add the total numbers and divide by the count

(defn aver
  [numbers]
    (if (empty? numbers)
      0
      (/ (reduce + numbers) (count numbers)))
      )

If I am to get the average of a list of [5 10] I'll not get the answer which should be 7.5, I'll only get the equation, how do I get otherwise?

 >(aver [5 10])
=> 15/2

2 Answers2

0

You can use bicdec to get a exact representation of that ratio. E.g.

user=> (let [numbers [1 1 1 2]] (bigdec (/ (reduce + numbers) (count numbers))))
1.25M
cfrick
  • 35,203
  • 6
  • 56
  • 68
0

Integer division in Clojure gives you rational numbers. If you want floating point numbers, one of the arguments needs to be a float. Or, you can pass the result to float.

(float (aver [5 10]))

`

Eric Ihli
  • 1,722
  • 18
  • 30
  • 1
    OP requested "exact" ;) – cfrick Sep 02 '19 at 06:01
  • Thanks Eric! Is there any chance you can pass that off in the function so you wouldn't have to use float in the REPL? I'm just experimenting at the moment – Ryan Jackson Sep 02 '19 at 06:04
  • One option would be to provide an initial value (that is a float) to the `reduce` form, like this: `(/ (reduce + 0.0 nums) (count nums))` where `nums` is a collection of numbers (list, vector, etc.) – Denis Fuenzalida Sep 02 '19 at 06:23