So I’ve been working on special functions, and to help with that I’ve created this class that implements an Iterator of Float values.
struct FloatIterator{T}<:AbstractVector{T}
min::T
max::T
FloatIterator{T}(min, max) where T = min > max ? error("max less than min") : new{T}(min,max)
end
FloatIterator{T}() where T =FloatIterator{T}(T(-Inf),T(Inf))
Base.iterate(it::FloatIterator) = (it.min, nextfloat(it.min))
function Base.iterate(it::FloatIterator{T}, el) where T
return el == it.max ? nothing : (el, nextfloat(el))
end
function Base.size(it::FloatIterator{T}) where T
if isless(it.max, 0.0)
size = reinterpret(Base.uinttype(T), it.max) - reinterpret(Base.uinttype(T), it.min)
elseif isless(-0.0, it.min)
size = reinterpret(Base.uinttype(T), it.max) - reinterpret(Base.uinttype(T), it.min)
else
size = reinterpret(Base.uinttype(T), it.max)
size += reinterpret(Base.uinttype(T), it.min) - reinterpret(Base.uinttype(T), T(-0.0))
end
return (size+1,)
end
Base.getindex(it::FloatIterator{T}, i::Int) where T = nextfloat(it.min, i-1)
Base.show(io::IO, mime::MIME"text/plain", it::FloatIterator) = show(io, it)
Base.show(io::IO, it::FloatIterator) = print(io, "FloatIterator(", it.min, ", ", it.max, ")")
It takes about 330μs
to loop through all Float16, and 24s
to loop through all Float32
.
Let me know if you think this should end up in a package somewhere or if similar functionality already exists!