Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are rational numbers implemented in Julia

Are the numerator and denominator stored as integers? Specifically, how are implemented the basic operations: sum, subtraction, multiplication, division?

like image 408
Alejandro Arcila Avatar asked Jan 25 '23 04:01

Alejandro Arcila


2 Answers

https://github.com/JuliaLang/julia/blob/248bbf6d61b643d0101bf96093cd7621e5bcf477/base/rational.jl#L9-L15

the code is fairly readable, in short:

struct Rational{T<:Integer} <: Real

means that both numerator and denominator have the same type, and that type is <: Integer.


if you want to know how some operations are implemented, try running this in your REPL:

julia> @edit 1//2 + 3//4

it should bring you to https://github.com/JuliaLang/julia/blob/248bbf6d61b643d0101bf96093cd7621e5bcf477/base/rational.jl#L285

like image 173
jling Avatar answered Jan 31 '23 09:01

jling


Even a faster and easier way to understand what is going on in Julia is just to use the dump command such as:

julia> dump(3//4)
Rational{Int64}
  num: Int64 3
  den: Int64 4
like image 28
Przemyslaw Szufel Avatar answered Jan 31 '23 10:01

Przemyslaw Szufel