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 floatingpoint 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=1e4)
3333//10000
julia> rationalize(0.987654321, tol=1e8)
987654321//1000000000
Common examples of its use:

Rationalize a floatingpoint number:
julia> rationalize(2.75) 11//4
This example approximates the floatingpoint number
2.75
as a rational number. 
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 specifyFloat64
as the type.  Control the tolerance for approximation:
julia> rationalize(0.333333333, tol=1e6) 1//3
By default, the tolerance
tol
is set toeps(x)
, which is the machine epsilon for the type ofx
. 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 nonzero 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.