Sunday, 24 January 2016

Julia: Rounding floating point numbers


If a floating point number don’t has exact representation, then by default that number is rounded to nearest representable value.
For example,

julia> x=2.1234567;

julia> x=x+0.1
2.2234567000000003

When I add 0.1 to 2.1234567, I am expection 2.2234567, but actual result is 2.2234567000000003. It is because, Julia rounded it to the nearest value.

Currently following rounding modes are supported by julia

a. RoundNearest
It is the default rounding mode, rounds the floating point to nearest number, with ties (fractional values of 0.5) being rounded to the nearest even integer.


You can get the current rounding mode using get_rounding method. You can set the rounding mode for given type using set_rounding method.

julia> get_rounding(Float64)
RoundingMode{:Nearest}()

julia> x=1.1;

julia> x=x+0.1
1.2000000000000002


b. RoundNearestTiesAway
Rounds to nearest integer, with ties rounded away from zero.

c. RoundNearestTiesUp
Rounds to nearest integer, with ties rounded toward positive infinity

d. RoundToZero
Returns the nearest integral value of the same type as x whose absolute value is less than or equal to x

julia> set_rounding(Float64,RoundingMode{:ToZero}())
0

julia> get_rounding(Float64)
RoundingMode{:ToZero}()

julia> x=1.1;

julia> x=x+0.1
1.2


e. RoundUp
Returns the nearest integral value of the same type as x that is greater than or equal to x.

julia> set_rounding(Float64,RoundingMode{:Up}())
0

julia> get_rounding(Float64)
RoundingMode{:Up}()

julia> x=1.1;

julia> x=x+0.1
1.2000000000000002

julia> x=x+0.1
1.3000000000000003

julia> x=x+0.1123
1.4123000000000003

julia> x=x+0.1
1.5123000000000004


f. RoundDown
Returns the nearest integral value of the same type as x that is less than or equal to x.

julia> get_rounding(Float64)
RoundingMode{:Down}()

julia> x=1.1;

julia> x=x+0.1
1.2


You can change the rounding mode for particular block of code using ‘with_rounding(f::Function, T, mode)’.

julia> with_rounding(BigFloat,RoundUp) do

           BigFloat(1) + parse(BigFloat, "0.001")

       end
1.001000000000000000000000000000000000000000000000000000000000000000000000000001






Previous                                                 Next                                                 Home

No comments:

Post a Comment