rationalize

rationalize([Type=Int,] x; tol=eps(x))

Approximate floating point number x as a Rational number with components of the given integer type. The result will differ from x by no more than tol.

Examples

In the Julia programming language, the rationalize() function is used to approximate a floating-point number x as a rational number with components of the given integer type. The resulting rational number will have a difference from x of no more than the specified tolerance tol.

julia> rationalize(1.5)
3//2

julia> rationalize(0.3333, tol=1e-4)
3333//10000

julia> rationalize(0.987654321, tol=1e-8)
987654321//1000000000

Common examples of its use:

  1. Rationalize a floating-point number:

    julia> rationalize(2.75)
    11//4

    This example approximates the floating-point number 2.75 as a rational number.

  2. Specify the type of the resulting rational number:

    julia> rationalize(Float64, 0.5)
    1//2

    The rationalize function can optionally take a type parameter to specify the type of the resulting rational number. Here, we specify Float64 as the type.

  3. Control the tolerance for approximation:
    julia> rationalize(0.333333333, tol=1e-6)
    1//3

    By default, the tolerance tol is set to eps(x), which is the machine epsilon for the type of x. You can also provide a custom tolerance to control the precision of the rational approximation.

Common mistake example:

julia> rationalize(1.23, tol=0)
ERROR: DomainError: Cannot rationalize number within zero tolerance

In this example, a tolerance of zero is provided, which results in a DomainError. Make sure to provide a non-zero tolerance value to avoid this error.

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.

*Required Field
Details

Checking you are not a robot: