Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reinterpret discards information and returns incorrect result #701

Open
antoine-levitt opened this issue May 21, 2024 · 4 comments
Open

Comments

@antoine-levitt
Copy link
Contributor

antoine-levitt commented May 21, 2024

using ForwardDiff
E(x) = abs2(x[1])
xf = randn(ComplexF64, 2)
# WRONG
r2c(x) = reinterpret(ComplexF64, x)
c2r(x) = reinterpret(Float64, x)
# # OK
# r2c(x) = x[1:2] + im*x[3:4]
# c2r(x) = vcat(real(x), imag(x))
ForwardDiff.gradient(x -> E(r2c(x)), c2r(x))
@antoine-levitt
Copy link
Contributor Author

The issue appears to be this somewhat unfortunate interaction:

julia> reinterpret(ComplexF64, ForwardDiff.Dual(1.0,1.0))
1.0 + 1.0im

@thomvet
Copy link
Contributor

thomvet commented Jun 3, 2024

Reinterpret just takes the number of bits of the ForwardDiff.Dual and makes them into a ComplexF64.

So, this result is very much expected and in my opinion not a bug.

@antoine-levitt
Copy link
Contributor Author

It makes sense technically, but it also means that the above example will fail: reinterpret works on the dual data structure, which is unusual (most operations apply to the primal variable). Is there any use for reinterpreting a dual in this way?

@KristofferC
Copy link
Collaborator

KristofferC commented Jun 4, 2024

There are many other cases like this. For example, eltype on a Vector{Dual{Float64}} will return Dual{Float64}. Or typeof of a dual number. At some point you have to be able to talk about the actual program that is running.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants