Reputation: 1581
I want to compare float values to determine the biggest number in the list.The precision of the float is fixed, 6 after the decimal.
Should I just compare them as integer and if they are equal then go and dig the values after the decimal ?
Upvotes: 0
Views: 6841
Reputation: 31
Following article provides various alternatives on comparing float values.. http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
Usually, finding the difference between the floats and checking if the difference is within the precision limit, helps in comparing the floats. But as also mentioned, there is no perfect answer and implementation for this because different between adjacent floats varies with the magnitude. Hence if you know the range of values which your program will use, then you can chose appropriate implementation for comparison.
Upvotes: 0
Reputation: 28882
use DBL_EPSILON as a basis for how close to doubles need to be.
use FLT_EPSILON exists for floats.
see this answer for a sample function that demonstrates the technique.
Upvotes: 1
Reputation: 613572
Code to do this looks like the following:
float MinFloatArray(float *a, int n)
{
int i;
float result = MAX_FLOAT;
for (i=0; i<n; i++)
if (a[i]<result)
result = a[i];
return result;
}
Upvotes: 0
Reputation: 91149
That depends on things you don't tell us.
etc.
As you have the values in a float array, I would do the following:
float biggest(float * values, int num)
{
int i;
float curmax;
if (num == 0) return NAN;
curmax = values[0];
for (i=1; i < num; i++) {
if (values[i] > curmax) curmax = values[i];
}
return curmax;
}
Upvotes: 0
Reputation: 11162
The easiest way to compare floats is with the <
operator, like so
if(float1 < float2)
printf("%f < %f\n", float1, float2);
Upvotes: 2
Reputation: 15633
If you want to find the biggest number, why would you need to worry about comparing for equality?
Upvotes: 0