gpbl
gpbl

Reputation: 4804

Max and min in an array of Float in Swift

According to this answer, to obtain the maximum of an array we can do:

let nums = [1, 6, 3, 9, 4, 6];
let numMax = nums.reduce(Int.min, { max($0, $1) })

How can we do the same for an Array<Float>, since there's no min and max for Float?

let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3];

Upvotes: 3

Views: 8253

Answers (6)

emraz
emraz

Reputation: 1613

Tested in Swift >= 5.0

let numbers = [12.9, 2.7, 3.7, 4, 5, 4, 12.8]
print(numbers.max() ?? 0) // Output 12.9
print(numbers.min() ?? 0) // Output 2.7

Upvotes: 0

NFarrell
NFarrell

Reputation: 255

Swift 4 has a .max() method for Array<Float>.

Example:

let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
let max = floats.max()

Note: max() returns an optional so there's a chance it could come back nil.

Upvotes: 2

William Hu
William Hu

Reputation: 16159

Swift 2:

var graphPoints:[Int] = [4, 2, 6, 4, 5, 8, 3]
let maxValue = graphPoints.maxElement()

Upvotes: 1

Martin R
Martin R

Reputation: 539945

The solution given here https://stackoverflow.com/a/24161004/1187415 works for for all sequences of comparable elements, therefore also for an array of floats:

let floats: Array<Float> = [2.45, 7.21, 1.35, 10.22, 2.45, 3]
let numMax = maxElement(floats)

maxElement() is defined in the Swift library as

/// Returns the maximum element in `elements`.  Requires:
/// `elements` is non-empty. O(countElements(elements))
func maxElement<R : SequenceType where R.Generator.Element : Comparable>(elements: R) -> R.Generator.Element

Upvotes: 8

codester
codester

Reputation: 37189

You can use -FLT_MAX which returns minimum magnitude of Float and used for same purpose

let numMax = floats.reduce(-FLT_MAX, { max($0, $1) })

For Double array you can use -DBL_MAX

If you want maximum magnitude value of Float use FLT_MAX.FLT_MIN is Minimum representable postive floating-point number.

Upvotes: 3

Antonio
Antonio

Reputation: 72760

Just use the first array element as the initial value:

let numMax = floats.reduce(floats[0], { max($0, $1) })

but of course you need to check that the floats array is not empty before doing it.

Upvotes: 6

Related Questions