开发者

Having a hard time working with floats

开发者 https://www.devze.com 2023-02-02 09:29 出处:网络
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 =

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.


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.


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).


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

0

精彩评论

暂无评论...
验证码 换一张
取 消