Skip to content

Commit 6b393f4

Browse files
authored
Int(::Dual) and Integer(::Dual) (#508)
1 parent ea822d2 commit 6b393f4

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "ForwardDiff"
22
uuid = "f6369f11-7733-5829-9624-2563aa707210"
3-
version = "0.10.18"
3+
version = "0.10.19"
44

55
[deps]
66
CommonSubexpressions = "bbf7d656-a473-5ed7-a52c-81e309532950"

src/dual.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,15 @@ end
305305
@inline Base.one(d::Dual) = one(typeof(d))
306306
@inline Base.one(::Type{Dual{T,V,N}}) where {T,V,N} = Dual{T}(one(V), zero(Partials{N,V}))
307307

308+
@inline function Base.Int(d::Dual)
309+
all(iszero, partials(d)) || throw(InexactError(:Int, Int, d))
310+
Int(value(d))
311+
end
312+
@inline function Base.Integer(d::Dual)
313+
all(iszero, partials(d)) || throw(InexactError(:Integer, Integer, d))
314+
Integer(value(d))
315+
end
316+
308317
@inline Random.rand(rng::AbstractRNG, d::Dual) = rand(rng, value(d))
309318
@inline Random.rand(::Type{Dual{T,V,N}}) where {T,V,N} = Dual{T}(rand(V), zero(Partials{N,V}))
310319
@inline Random.rand(rng::AbstractRNG, ::Type{Dual{T,V,N}}) where {T,V,N} = Dual{T}(rand(rng, V), zero(Partials{N,V}))

test/DualTest.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,19 @@ end
505505
@test !isfinite(dinf)
506506
end
507507

508+
@testset "Integer" begin
509+
x = Dual(1.0,0)
510+
@test Int(x) Integer(x) convert(Int,x) convert(Integer,x) 1
511+
x = Dual(1.0,0,0)
512+
@test Int(x) Integer(x) convert(Int,x) convert(Integer,x) 1
513+
@test_throws InexactError Int(Dual(1.5,1.2))
514+
@test_throws InexactError Integer(Dual(1.5,1.2))
515+
@test_throws InexactError Int(Dual(1,1))
516+
@test_throws InexactError Integer(Dual(1,1,2))
517+
@test length(UnitRange(Dual(1.5), Dual(3.5))) == 3
518+
@test length(UnitRange(Dual(1.5,1), Dual(3.5,3))) == 3
519+
end
520+
508521
if VERSION >= v"1.6.0-rc1"
509522
@testset "@printf" begin
510523
for T in (Float16, Float32, Float64, BigFloat)

0 commit comments

Comments
 (0)