with_rounding
with_rounding(f::Function, T, mode)
Change the rounding mode of floating point type T for the duration of f. It is logically equivalent to:
old = get_rounding(T)
set_rounding(T, mode)
f()
set_rounding(T, old)
See get_rounding for available rounding modes.
Examples
In the Julia programming language, the with_rounding function allows you to change the rounding mode of a floating point type T for the duration of a given function f. It follows the logical steps:
- Save the current rounding mode of type
Tusingget_rounding(T). - Set the rounding mode of type
Tto the desiredmodeusingset_rounding(T, mode). - Execute the function
f(). - Restore the original rounding mode of type
Tusingset_rounding(T, old).
Here are some examples of how to use the with_rounding function:
-
Round a floating-point operation with different rounding modes:
julia> x = 1.5; julia> with_rounding(RoundDown, Float64) do x = x / 2 end 0.75In this example, the value of
xis divided by 2 using theRoundDownrounding mode. -
Calculate the square root with increased precision:
julia> precision = BigFloat.precision; julia> with_rounding(RoundUp, BigFloat) do sqrt(BigFloat(2)) end 1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573This example calculates the square root of 2 with increased precision using the
RoundUprounding mode. - Perform a custom rounding operation:
julia> with_rounding(RoundNearest, Float64) do round(Int, 3.7) end 4Here, the
roundfunction is called within thewith_roundingcontext to perform rounding to the nearest integer.
Remember that get_rounding provides available rounding modes for a specific floating point type.
See Also
cmp, float, get_bigfloat_precision, get_rounding, get_zero_subnormals, isapprox, maxintfloat, mod2pi, nextfloat, precision, prevfloat, rationalize, round, set_bigfloat_precision, set_rounding, set_zero_subnormals, significand, with_bigfloat_precision, with_rounding,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.