Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write method to calculate average in Swift-playground

In swift I'm trying to write a method to calculate the average. Using the method below if i type average(5,10,15) I get infinity displayed in the swift-playforund

func average(numbers: Int...) -> Double {
    var sum = 0
    var count = 0
    for number in numbers {
        sum += number
    }
    var  ave : Double = Double(sum) / Double(count)
    return ave
}
like image 398
user1898829 Avatar asked Jun 09 '14 09:06

user1898829


People also ask

How do you calculate average in Swift?

We know that average is calculated as the sum of elements divided by the number of elements. So let us divide the sum by length to get the average as result and print it. Here, we have converted the types of sum and length to Double to get the result in decimal.

How do you find average method?

The most widely used method of calculating an average is the 'mean'. When the term 'average' is used in a mathematical sense, it usually refers to the mean, especially when no other information is given. Add the numbers together and divide by the number of numbers. (The sum of values divided by the number of values).

How do I find the average of a set of data?

You can find the mean, or average, of a data set in two simple steps: Find the sum of the values by adding them all up. Divide the sum by the number of values in the data set.

What is average method in math?

Average Formula in Maths The formula to find the average of given numbers or values is very easy. We just have to add all the numbers and then divide the result by the number of values given. Hence, the average formula in Maths is given as follows: Average = Sum of Values/ Number of values.


9 Answers

import Accelerate

let avg = vDSP.mean(array)

This will be at least 50x faster than all other solutions posted so far.

like image 134
John Scalo Avatar answered Oct 30 '22 03:10

John Scalo


It's so much easier with just a straightforward call to reduce:

let array = [1.0,2.0,3.0]
var average = array.reduce(0.0) {
    return $0 + $1/Double(array.count)
}
// average = 2.0
like image 23
GarlicFries Avatar answered Oct 30 '22 03:10

GarlicFries


You can use the count property of the array:

func average(numbers: Int...) -> Double {
    var sum = 0
    for number in numbers {
        sum += number
    }
    var  ave : Double = Double(sum) / Double(numbers.count)
    return ave
}
like image 39
Jens Wirth Avatar answered Oct 30 '22 01:10

Jens Wirth


While others have already pointed out the missing count variable, it is worth noting that you can do the average even more elegantly by using closures as follows:

func averagec(numbers:Int...) -> Double {
    return Double(numbers.reduce(0,combine:+))/Double(numbers.count)
}

Edited for Swift 4:-

func averagec(numbers:Int...) -> Double {
    return Double(numbers.reduce(0,+))/Double(numbers.count)
}
like image 40
Maria Zverina Avatar answered Oct 30 '22 01:10

Maria Zverina


Just write count = count +1 in your for loop.

Such like,,,

.
.
.
for number in numbers 
{
  sum += number
  count = count +1
}
.
.

And now function by

var avg:Double = average(5,10,15)
println(avg)
like image 41
iPatel Avatar answered Oct 30 '22 02:10

iPatel


You forget to increment count in the inner loop.

like image 38
Anton Gogolev Avatar answered Oct 30 '22 03:10

Anton Gogolev


You're getting infinity because count is always 0 - it's never incremented. So the ave variable is always going to be equal to some number over 0, which is a divide by zero error.

Either use countElements(numbers) or increment count on each iteration through the loop.

like image 39
Bill Avatar answered Oct 30 '22 02:10

Bill


Here's what I did:

func getAverage(nums: Double...) ->Double
{
    var temp = 0.0
    for num in nums
    {
        temp+=num
    }
    let div = Double(nums.count)
    var average = temp/div
    return average
}
getAverage(21,34.5,28,79)

Note that I'm accepting Doubles as input, not just Ints. I'm being a little verbose at the end, but I was trying for readable code. I probably could have just returned:

 return temp/Double(nums.count)

at the end and saved a few lines of code.

like image 27
james Burns Avatar answered Oct 30 '22 03:10

james Burns


Swift 3, functional style

func average(numbers: Int...) -> Double {
    assert(numbers.count > 0)
    return numbers.reduce(0, {$0 + Double($1)})/Double(numbers.count)
}
like image 41
wcochran Avatar answered Oct 30 '22 02:10

wcochran