My Coding >
Programming language >
Perl >
Perl FAQ >
Perl: Rounding, How to round float
Perl: Rounding, How to round floatRounding is a bit complicated in Perl. This is related with non-ideal float presentation in memory and also with different techniques used for rounding Problem with float presentation in PerlActually, this is not pure Perl problem — this is a general problem of float presentation in memory. Let's imagine, we would like to investigate different routines fro rounding in Perl and create some set of floats for tests. We will make floats in range[-2, 2] with step 0.1
and … the result is shocking!
It is possible to see, that in the range [-1.0 and 1.0], the floats are slightly different from what we expect from our cycle. And this tiny difference will give very different results if we will use this data for rounding properties. Therefore we need to use explicit task for rounding, without preliminary calculations. And also it is possible to see, that despite we required to make floats up to 2.0 inclusively, Perl not use 2.0 as a last float, stopping at 1.9 Therefore in further tests we will use hand typed floats, to clearly understand how rounting is working in Perl
But to make picture more clear I will remove some data which not give any extra information and use only these data: (-2, -1.9, -1.5, -1.4, -1, -0.9, -0.5, -0.4, -0.1, 0, 0.4, 0.5, 0.6, 0.9, 1, 1.4, 1.5, 1.9, 2) Tools for rounding in PerlThere are a lot of different functions in Perl designed for rounding values and also you can write your own functions:
What to use for rounding in PerlAs you can see from this resulting table, the correct rounding can only be performed by Math::Round::round() and our R2 = int($i + $i/abs($i*2 || 1)) function. If you read more about Math::Round module, you can find a lot of different rounding techniques there. Another interesting result - sprintf() - give proper rounding as well, but if you check rounding for 0.5 and 1.5 you will see, that this is so called Round half to even technique. This rounding is used for reduce bias in calculations. How to round to given precision in PerlEverything we’ve discuss here was rounding to ineger value, but what should we do, if we need to round for some precision after coma?
Or you can use precision in the sprintf() if you are happy to use round half to even procedure.
|
Last 10 artitles
9 popular artitles
|
|||
© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. |