Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float divison and casting in Swift

I'm trying to learn Swift and I made a simple average function:

func average(numbers: Int...) -> Float {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return Float(sum)/Float(numbers.count)
}
average(1,2,3,4,5,6)

This gives me the correct result: 3.5 However, I am wondering why I have to cast both sum and numbers.count to floats. I tried casting this way:

return Float(sum/numbers.count)

but it gives me just 3.0

like image 632
Tomasero Avatar asked Aug 06 '14 00:08

Tomasero


People also ask

How do you split a float in Swift?

Divison of Float gives a result in this case of 3.5. divides the integer "sum" by the integer "numbers. count". Division of integers gives an integer result, which is the integer quotient disregarding any remainder.

What is a float in Swift?

Floating-Point Numbers Swift provides two signed floating-point number types: Double represents a 64-bit floating-point number. Float represents a 32-bit floating-point number.

What is the difference between floating point and integer division?

The division operator / means integer division if there is an integer on both sides of it. If one or two sides has a floating point number, then it means floating point division.


2 Answers

return Float(sum/numbers.count) 

In this statement, sum and numbers.count are both Ints, so they use an Int division function which returns an Int. Since an Ints only have whole values, this result loses any decimal precision. A Float is then created from this Int and it has decimal digits, but the precision has already been lost at this point.

return Float(sum)/Float(numbers.count)

In this statement, Floats are made out of sum and numbers.count, then divided. Because they are Floats this time, a division function for Floats is used which returns a Float. In this statement the precision is never lost, so it returns a more accurate result.

like image 36
Connor Avatar answered Sep 29 '22 11:09

Connor


First, you should use Double and not Float. Float gives you very limited precision. Why you would want 6 digits precision with Float when you could have 15 digits with Double is hard to understand.

Second, a compiler does exactly what you tell it.

Float (sum) / Float (numbers.count)

takes the integer "sum", takes the integer "numbers.count", converts both to Float and divides. Divison of Float gives a result in this case of 3.5.

Float (sum/numbers.count)

divides the integer "sum" by the integer "numbers.count". Division of integers gives an integer result, which is the integer quotient disregarding any remainder. 21 / 6 equals 3 with a remainder of 3. So the result of the division is 3, which you then convert to the Float 3.0.

like image 127
gnasher729 Avatar answered Sep 29 '22 11:09

gnasher729