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:

1. Save the current rounding mode of type `T` using `get_rounding(T)`.
2. Set the rounding mode of type `T` to the desired `mode` using `set_rounding(T, mode)`.
3. Execute the function `f()`.
4. Restore the original rounding mode of type `T` using `set_rounding(T, old)`.

Here are some examples of how to use the `with_rounding` function:

1. Round a floating-point operation with different rounding modes:

``````julia> x = 1.5;
julia> with_rounding(RoundDown, Float64) do
x = x / 2
end
0.75``````

In this example, the value of `x` is divided by 2 using the `RoundDown` rounding mode.

2. Calculate the square root with increased precision:

``````julia> precision = BigFloat.precision;
julia> with_rounding(RoundUp, BigFloat) do
sqrt(BigFloat(2))
end
1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573``````

This example calculates the square root of 2 with increased precision using the `RoundUp` rounding mode.

3. Perform a custom rounding operation:
``````julia> with_rounding(RoundNearest, Float64) do
round(Int, 3.7)
end
4``````

Here, the `round` function is called within the `with_rounding` context to perform rounding to the nearest integer.

Remember that `get_rounding` provides available rounding modes for a specific floating point type.