开发者

What is the difference between round() & trunc() function?

I am ve开发者_如何转开发ry confused about these functions?


In mathematics, rounding means rounding to the nearest integer, so rounding 3.4 results in 3 and rounding 3.6 results in 4.

Truncating, on the other hand, means removing the fractional part altogether, so either 3.4 or 3.6 results in 3.

Most programming languages and libraries follow this as well.


round( ) and trunc( ), in most programming languages, correspond to two of the four basic rounding modes specified by the IEEE-754 standard.

The four rounding modes, the corresponding rounding functions, and examples of how they behave on a variety of inputs, are:

rounding mode       function [1]     results of rounding:
                                     0.2    1.7   -2.6   -3.3
---------------------------------------------------------------------------------
round to nearest    round( ) [2]     0.0    2.0   -3.0   -3.0
round to zero       trunc( )         0.0    1.0   -2.0   -3.0
round to +infinity  ceil( )          1.0    2.0   -2.0   -3.0
round to -infinity  floor( )         0.0    1.0   -3.0   -4.0

[1] the IEEE-754 standard doesn't require these names, and not all languages use the same names. These are merely the most common names in my experience.

[2] the round( ) function in C and C-derived languages does not correspond exactly to the IEEE-754 round-to-nearest rounding mode. Specifically, it differs in it's handling of exact halfway cases. The C round( ) function rounds "ties away from zero", which is probably what you learned in elementary school, but introduces bias into certain calculations. The IEEE-754 round to nearest mode specifies that ties be rounded to the nearest even number, which is less likely to introduce bias while maintaining determinism.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜