How to define function parameters to be read as same type?


This is how I’m defining the function.

function unrestricted_search(f::Function, δ::T, x0::T) where T# Maximization algorithm
    f0 = f(x0)
    Data = DataFrame(f=f0, x=x0)
    diff = f(x0+δ) - f(x0)
    if diff < 0
        δ = -δ
    x1 = x0 + δ
    push!(Data, (f=f(x1), x=x1))
    while Data.f[end-1] < Data.f[end]
        x = x0 + n*δ
        push!(Data, (f=f(x), x=x))
        n += 1
    Optima = Data[n-1, :]
    return Data, n, Optima

When I call the function with unmatching data types,

unrestricted_search(f, 0.1, 0)

It results in the following error.

LoadError: InexactError: Int64(0.1)
InexactError: Int64(0.1)

Is there a way to automatically read the input as Float64 if one of them is float?

Also, as a side note. I created the following function for testing

function addition(x1::T, x2::T) where T
    x3 = x1 + x2

which results in the following error

LoadError: MethodError: no method matching addition(::Float64, ::Int64)
e[0mClosest candidates are:
e[0m  addition(::T, e[91m::Te[39m) where T at In[57]:1
MethodError: no method matching addition(::Float64, ::Int64)
Closest candidates are:
  addition(::T, ::T) where T at In[57]:1

Why are the errors different ?

Your function has a lot of overhead by doing optimization in a DataFrame. I would suggest you don’t specify the types at all

you probably don’t care about them being the same type. You can always:

julia> x, y = promote(0.1, 0)
(0.1, 0.0)

It seems to me the first error happens because you are creating a DataFrame with an integer column, and then try to push floats to it. You can do Float64(x0) in creating the DataFrame to get a float column.

The second error is because addition(x1::T, x2::T) where T means x1 and x2 have to have the same type. That should also affect your first definition though, are you sure you haven’t defined this function multiple times in different ways and are calling old methods?

Thanks for the clarification. No, the function is defined once. Also, when I defined as a normal function (without defining type T), the first function was throwing the same error. I guess its due to the DataFrame as mentioned above.