dev
dev

Reputation: 536

Calculate average of array in Scala - Result truncated

I've been learning Scala for a few days with TDD, so I have the following Unit Test:

test("CalcStats.calculateAverage should return average") {
    assert(CalcStats.calculateAverage(Array(6, 9, 15, -2, 92, 11)) === 21.833333)
  }

As far as I think, the following should make it pass:

def calculateAverage(values: Array[Int]): Float = {
    values.sum / values.size
  }

However, I am getting 21.0 instead of 21.833333, so the Unit Test will fail ❌

Expected :21.833333
Actual   :21.0

As long as I am specifying that the result will be a Float, I thought that was enough, but it is definitely not. What should I do to avoid the truncation in the result?

Thanks in advance.

Upvotes: 0

Views: 393

Answers (2)

morbvel
morbvel

Reputation: 61

This method should work - just a simple recursive method to add all the values from the list and, when empty, divide with the total size of the list.

def getAverage(list: List[Double]): Double = {
  def loop(list: List[Double], acc: Double = 0): Double = {
    list match {
      case Nil => acc / list.size
      case element :: tail => loop(tail, acc + element)
    }  
  }

  loop(list)
}

Upvotes: 0

Oleg Zinoviev
Oleg Zinoviev

Reputation: 559

In

def calculateAverage(values: Array[Int]): Float = {
values.sum / values.size}

underlying result values.sum / values.size has type Int (21) So, the compiler extend it to Float. Try the following:

def calculateAverage(values: Array[Int]): Float = {
values.sum.toFloat / values.size  }

Upvotes: 2

Related Questions