As mentioned in the comments, the best way is to use Rational type. E.x., A = Rational{Int}[1 2;3 4]
, to get the output in your desired format use, A*float(inv(A))
. Credits to @mschauer.
To elaborate a little, the floating point numbers typically used in computation have limited precision, and cannot represent all real numbers. Hence, you get these kinds of errors when operating with floating point numbers. See links in the comments for details on this issue.
Julia however makes it very easy to define other numeric types, and operate on them if you want. One of them is a rational number type, which can represent fractions exactly. We can create the array as rationals:
julia> A = Rational{Int}[1 2;3 4]
2x2 Array{Rational{Int64},2}:
1//1 2//1
3//1 4//1
Then, operations on this array will return exact rational results
julia> A*(inv(A))
2x2 Array{Rational{Int64},2}:
1//1 0//1
0//1 1//1
If we want the results as floating point numbers, they can be converted at the end of the computation.
julia> float(A*(inv(A)))
2x2 Array{Float64,2}:
1.0 0.0
0.0 1.0
It is important to note that the reason floating point numbers are used by default is performance. CPU's are optimised to operate on floating point numbers, and using rationals as above is going to be much slower. Julia however gives you the tools to allow you to make that choice yourself, based on your own needs.