Thursday, July 30, 2009

Both int and float expressions?

programming in C beginner....


can both int and float expressions suffer round-off errors and/or are they always computed exactly? please advise.

Both int and float expressions?
Yes, both can experience round off errors. With floating point, this is the norm, it typically loses accuracy over so many operations. With int, it is less likely to suffer roundoff errors. Math performed with integers alone cannot ever have roundoff errors, but if you are performing math operations on floating point values and casting them to int, then they suffer the same potential for roundoff errors that floating point does.
Reply:Yes, any value on a computer can suffer from round off errors because computers are finite machines. Since both int and float are stored with a finite amount of memory, they can both only represent a finite number of values. In order to fit a world of infinite values into this finite computer world, you have to make some trade-offs.





For example, if you store an repeating number, such as 2/3, in a float, it will be truncated to be a non-repeating number so it can be stored as a float. So 0.6666666... gets changed to 0.66667. Likewise is true with irrational numbers.





For an int, storing any non-integer value will result in round off error. so storing 1.1, 1.2, or 1.3484615 in to an int will result in the int having a value of 1.


No comments:

Post a Comment