user513638
user513638

Reputation:

Having a hard time working with floats

I wasn't really sure what to name the title.

I'm checking to see if the value of two floats are the same. If I use printf() or NSLog(), the values return 0.750000. However, a line like if (value1 == value2) { return TRUE; } doesn't work. I can assume that in reality, the floats are beyond the 7 decimal places, and printf() / NSLog() can't return a value beyond 7 decimals.

I tried googling a way to see how I could cut down a float to a smaller amount of decimal places, or simply convert it to another data type, but I didn't get such luck so far.

Upvotes: 0

Views: 778

Answers (3)

whjou
whjou

Reputation: 156

You might want to peek at float.h (http://www.gnu.org/software/libc/manual/html_node/Floating-Point-Parameters.html) for a non-arbitrary definition of epsilon. In particular, FLT_EPSILON and FLT_DIG.

Upvotes: 4

Mitch Wheat
Mitch Wheat

Reputation: 300759

When ever you compare floating point numbers you need to use a tolerance:

if (Abs(value1 - value2) < epsilon)
{
}

where epsilon is a value such as 0.000001

Upvotes: 0

D&#233;j&#224; vu
D&#233;j&#224; vu

Reputation: 28850

You can decide of an epsilon that is the maximum value under which number are equals. Like

  #define EPSILON 0.0001

  if (fabs(floatA - floatB) < EPSILON) { retun TRUE; }

fabs(x) returns the absolute value of the double x.

You may also want to use the double instead of float data type (double is twice the size of a float).

Upvotes: 1

Related Questions