Jiayan Yang
Jiayan Yang

Reputation: 101

inexact error in Julia -- matrix calculation

The error happens after else condition. I want to replace A's column by new one. The following is the datatype of variables.It seems that it is datatype issue.

A = [1 1 1 1 1 0 0;
     1 2 0 3 0 1 0;
     2 1 2 0 0 0 -1;
     2 3 1 1 0 0 0]
b = [20 24 16 20]'
c = [-1 -2 -3 -4 0 0 0]'
C = [1 5 6 4]'

## convert the datatype of original data
C = vec(C)
# initial basis matrix
B = A[:, C]
# initial basic solution
x = inv(B)*b
c_B = c[C]
# initial reduced costs
c_r = (c' - c_B'*inv(B)*A)'
# if basic matrix is not identity (e.g., take other variables other than slack
# variables as starting point), convert B=I and N=inv(B)
ind = eye(length(C))
j = 1
if B != ind
    for i in length(c)
        if i in C
            A[:,i] = ind[:,j]
            j += 1
        else
            A[:,i] = inv(B)*A[:,i]
        end
    end
end

Upvotes: 1

Views: 1095

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

You have the following problems the code. First A is Matrix{Int64} and it should be Matrix{Float64}. You can fix it by writing:

A = Float64[1 1 1 1 1 0 0;
            1 2 0 3 0 1 0;
            2 1 2 0 0 0 -1;
            2 3 1 1 0 0 0]

Second - you probably want index i to range from 1 to length(c) so you should write your loop as:

for i in 1:length(c)

Finally - your code will not work under Julia 1.0 not only because eye is not defined, but also because you update variable j inside a loop. I would recommend you to wrap the whole code in a function or write global j += 1 for it to work under Julia 1.0.

EDIT:

The problem - in a nutshell is the following:

julia> A = [1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> A[1] = 0.5
ERROR: InexactError: Int64(Int64, 0.5)

Array A can hold only integers, so you cannot assign a float to it. By writing Float64 in front of array literal you force it to have another type of element, so this works:

julia> A = Float64[1,2,3]
3-element Array{Float64,1}:
 1.0
 2.0
 3.0

julia> A[1] = 0.5
0.5

julia> A
3-element Array{Float64,1}:
 0.5
 2.0
 3.0

In short Julia knows if your array holds integers or floats and checks it. Sometimes type promotion is allowed (e.g. you can assign an integer to an array of floats as this normally does not lead to the loss of precision) as is explained here https://docs.julialang.org/en/latest/manual/conversion-and-promotion/#Conversion-1.

Upvotes: 4

Related Questions