Skip to content

Can't differentiatate through StepRangeLen due to TwicePrecision #380

Open
@howthebodyworks

Description

@howthebodyworks

There is one very common data type that we can't differentiate through - StepRangeLen, which is what we usually get back from range.

julia> using ForwardDiff

julia> f1v(x::Vector) = sum(range(0; step=0.1, stop=2)*x[1]);  # edited not to clash with definitions below

julia> g1v = x -> ForwardDiff.gradient(f1v, x);

julia> f1v([1.0])
31.5

julia>  g1v([1.0])
MethodError: no method matching twiceprecision(::Base.TwicePrecision{ForwardDiff.Dual{ForwardDiff.Tag{typeof(f1),Float64},Float64,1}}, ::Int64)
Closest candidates are:
  twiceprecision(!Matched::T<:Union{Float16, Float32, Float64}, ::Integer) where T<:Union{Float16, Float32, Float64} at twiceprecision.jl:220
  twiceprecision(!Matched::Base.TwicePrecision{T<:Union{Float16, Float32, Float64}}, ::Integer) where T<:Union{Float16, Float32, Float64} at twiceprecision.jl:225

This problem does not arise with numerically equivalent data types which do not use TwicePrecision, such as LinRange:

julia> using ForwardDiff

julia> f2(x::Vector) = sum(LinRange(0, 2, 21)*x[1]);

julia> g2 = x -> ForwardDiff.gradient(f2, x);

julia> f2([1.0]), g2([1.0])
(21.0, [21.0])

Related: JuliaMath/Interpolations.jl#293

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions