Reputation: 23
For an input like the following is it ok to use Float.compare
to find the biggest float in an array?
Float[] v = {0.38118651972530804, 0.3580139606405057, 0.7358862700995704};
float max = -1;
for (int i = 0; i < v.length; i++)
if (Float.compare(max,v[i]) > 0) max = v[i];
Is there a better way? or maybe there could be some precision error?
Upvotes: 2
Views: 120
Reputation: 424993
How about one line:
Float max = Collections.max(Arrays.asList(v));
Upvotes: 0
Reputation: 18702
How about this-
float max = v[0]; // the first item in array
// Loop through all items starting the second one
for (int i = 1; i < v.length; i++)
{
if (v[i] > max) // If current item is bigger, update max to current item
{
max = v[i];
}
}
Upvotes: 0
Reputation: 2328
There can be errors if all the values in the array are less than -1. Better to initialize max as v[0].
And, your code finds the smallest element. Not the largest element.
Float[] v = {0.38118651972530804, 0.3580139606405057, 0.7358862700995704};
float max = v[0];
for (int i = 1; i < v.length; i++)
if (Float.compare(max, v[i]) < 0) max = v[i];
Upvotes: 0
Reputation: 534
I'd use a collection and call the max() method. See: here
Upvotes: 2