开发者

Typecasting a floating value or using the math.h floor* functions?

开发者 https://www.devze.com 2022-12-25 08:18 出处:网络
I am coding up an implementation of Interpolation Search in C. The question is actually rather simple, I need to use the floating operations to do linear interpolation to find the correct index which

I am coding up an implementation of Interpolation Search in C.

The question is actually rather simple, I need to use the floating operations to do linear interpolation to find the correct index which will eventually be an integer result.

In particular my probe index is:

t = i + floor((((k-low)/(high-low)) * (j-i)));

where, i,j,k,t are unsigned ints, and high,low are doubles.

Would this be equivalent to:

t = i + (unsigned int)(((k-low)/(high-low)) * (j-i));

Is there any reason I would actual开发者_运维技巧ly want to use math.h floor* functions over just a simple (int) typecast?


They are different when the value is < 0.

floor(-1.5) = -2.0
(int)-1.5 = 1


They are equivalent only for positive numbers. From the C99 specification (§6.3.1.4/1):

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

So, for positive numbers, the result of casting a floating-point value to an integral type is equivalent to calling floor, but for negative number is is equivalent to calling ceil.


In your case, they are equivalent. But for negative numbers,

g++> printf("%g %d %u\n", floor(-5.5), (int)(-5.5), (unsigned)(-5.5));
-6 -5 0

(actually, casting a negative real number ≤ -1 to unsigned integer is implementation-defined (or undefined behavior?).)

Also, floor returns a double, so i + floor(...) will be performed as a floating point operation instead of an integer operation.

0

精彩评论

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

关注公众号