St Ax
St Ax

Reputation: 83

Julia InexactError: Int64

I am new to Julia. Got this InexactError . To mention that I have tried to convert to float beforehand and it did not work, maybe I am doing something wrong.

column = df[:, i]  
max = maximum(column)
min = minimum(column)
scaled_column = (column .- min)/max   # This is the error, I think
df[:, i] = scaled_column
julia> VERSION
v"1.4.2"

Upvotes: 4

Views: 10223

Answers (2)

StefanKarpinski
StefanKarpinski

Reputation: 33249

Hard to give a sure answer without a minimal working example of the problem, but in general an InexactError happens when you try to convert a value to an exact type (like integer types, but unlike floating-point types) in which the original value cannot be exactly represented. For example:

julia> convert(Int, 1.0)
1

julia> convert(Int, 1.5)
ERROR: InexactError: Int64(1.5)

Other programming languages arbitrarily chose some way of rounding here (often truncation but sometimes rounding to nearest). Julia doesn't guess and requires you to be explicit. If you want to round, truncate, take a ceiling, etc. you can:

julia> floor(Int, 1.5)
1

julia> round(Int, 1.5)
2

julia> ceil(Int, 1.5)
2

Back to your problem: you're not calling convert anywhere, so why are you getting a conversion error? There are various situations where Julia will automatically call convert for you, typically when you try to assign a value to a typed location. For example, if you have an array of Ints and you assign a floating point value into it, it will be converted automatically:

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

julia> v[2] = 4.0
4.0

julia> v
3-element Array{Int64,1}:
 1
 4
 3

julia> v[2] = 4.5
ERROR: InexactError: Int64(4.5)

So that's likely what's happening to you: you get non-integer values by doing (column .- min)/max and then you try to assign it into an integer location and you get the error.

Upvotes: 7

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69819

As a side note you can use transform! to achieve what you want like this:

transform!(df, i => (x -> (x .- minimum(x)) ./ maximum(x)) => i)

and this operation will replace the column.

Upvotes: 1

Related Questions