Rational numbers
7.4. Rational numbersΒΆ
Rational numbers (ratios of integers) can be represented exactly in Julia using the //
operator:
a = 355 // 113
355//113
Rational numbers can be converted to floating point numbers if needed:
Float64(a)
3.1415929203539825
However, this is often not needed since many standard operations and comparison operators are defined directly using the rational number type: (from the Julia documentation)
julia> 2//3 == 6//9
true
julia> 2//3 == 9//27
false
julia> 3//7 < 1//2
true
julia> 3//4 > 2//3
true
julia> 2//4 + 1//6
2//3
julia> 5//12 - 1//4
1//6
julia> 5//8 * 3//12
5//32
julia> 6//5 / 10//7
21//25
Note that if the numerator and the denominator have common factors, they are reduced to the lowest terms such that the denominator is positive: (from Julia documentation)
julia> 6//9
2//3
julia> -4//8
-1//2
julia> 5//-15
-1//3
julia> -4//-12
1//3
When combined with other numeric types, the rational numbers will be promoted to give the expected result: (from the Julia documentation)
julia> 3//5 + 1
8//5
julia> 3//5 - 0.5
0.09999999999999998
julia> 2//7 * (1 + 2im)
2//7 + 4//7*im
julia> 2//7 * (1.5 + 2im)
0.42857142857142855 + 0.5714285714285714im
julia> 3//2 / (1 + 2im)
3//10 - 3//5*im
julia> 1//2 + 2im
1//2 + 2//1*im
julia> 1 + 2//3im
1//1 - 2//3*im
julia> 0.5 == 1//2
true
julia> 0.33 == 1//3
false
julia> 0.33 < 1//3
true
julia> 1//3 - 0.33
0.0033333333333332993