Log in

View Full Version : Type conversion


Zolfresh
Jun 1, 2015, 08:58 PM
I came to know that the correct way to round off a floating number x to an integer value is

y = (int) (x + 0.5)

I couldn't understand. Why is the fraction 0.5 (and not anything else) added to x?
Moreover, what actually the prefix (int) is doing here?

Oliver2011
Jun 1, 2015, 09:53 PM
Floating Point Issues - C Programming Questions and Answers Discussion Page For Q.135 (http://www.indiabix.com/c-programming/floating-point-issues/discussion-135)

There's explanation and discussion board that will help.

ScottGem
Jun 2, 2015, 05:47 AM
The INT function in most languages (and you need to specify the language you are working in) will truncate x to the lowest integer. So 10 and 10.8 will be come 10. So, if you add .5 to the number it will bring it to the next integer. So 10.3 will become 10.8 and still return 10. But 10.8 will become 11.3 and return 11.

Zolfresh
Jun 2, 2015, 07:50 AM
If the integer function really does so then I think it is nothing but the 'floor function' as in Discrete Mathematics. The floor of a real number x returns the largest integer that is less than or equal to x.

For example, floor(4.6)=4, floor(-4.6)=-5

This is different from the truncation function in the way that

trunc(4.6)=4 but trunc(-4.6)=-4

But if this is the case it should have been language independent. Since discrete structures are static and not language dependent. The domain of languages are dynamic. Day in and day out languages evolve and vanish. But the rule remains. Compiler vendors are interpreting these rules in their own way, giving them unique names and selling them... we are suffering. There should be a standard. But that cannot be the case because of different operating systems are there, and each compiler is targeted for a specific OS. OSs are in turn dependent on Hardware specifications of the system that it runs on, and there are thousands of different hardware specifications too.

And surprisingly, C does not follow the rule of floor function, I found. Rather it follows the truncation function.
That is why it shows

(int)4.6=4 and (int)-4.6=-4

Which means that the formula y=(int)(x+0.5) would not correctly round off x if applied in C.
Perhaps that is why C has ready-made library functions 'floor()' and 'ceil()' to get the job done.

Thus according to me, y=floor(x+0.5) is more general and y=(int)(x+0.5) is language dependent because each language will treat the 'int' differently.

ScottGem
Jun 2, 2015, 08:11 AM
You probably know more about mathematics than I do. I have no clue what a floor function is or does. I do know that, as stated, the Integer function in most languages, truncates a number by removing the decimal portion, leaving only the integer portion. That's why most languages include a Round function that will round a number to its nearest value.