3

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];

6 Answers 6

8

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
Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

3

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.

3 Comments

Thanks, I wasn't aware of FLT_MIN.
It should be -FLT_MAX that for minimum magnitude value for Float.FLT_MIN gives minimum vale of exponent.So i am changing my answer
Where can I find the documentation of those variables?
2

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.

Comments

1

Swift 2:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.