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

sqrt(::Matrix{Float64}) is not type stable #1130

Open
LilithHafner opened this issue Nov 30, 2024 · 3 comments
Open

sqrt(::Matrix{Float64}) is not type stable #1130

LilithHafner opened this issue Nov 30, 2024 · 3 comments
Labels
performance Must go faster

Comments

@LilithHafner
Copy link
Member

julia> using StableRNGs

julia> rng = StableRNG(0)
StableRNGs.LehmerRNG(state=0x00000000000000000000000000000001)

julia> sqrt(rand(rng,3,3))
3×3 Matrix{ComplexF64}:
    0.410548+0.369007im      0.49482-0.209855im   0.394519-0.231836im
 -0.00928873+0.0595217im    0.935186-0.0338502im   0.11389-0.0373957im
    0.661866-0.458654im   -0.0589303+0.260838im   0.524852+0.288158im

julia> sqrt(rand(rng,3,3))
3×3 Matrix{Float64}:
 0.301226   0.392135   -0.452243
 0.183647   0.25732     1.14379
 0.185353  -0.0785732   0.578105

For scalars, we throw when sqrting a negative unless the negative is of a complex type in which case we return a complex result. IMO that is a much better solution. Switching to that would be breaking in the case of square rooting real matrices with negative real eigenvalues.

@LilithHafner LilithHafner added the performance Must go faster label Nov 30, 2024
@jishnub
Copy link
Collaborator

jishnub commented Dec 1, 2024

Previous discussion in #21

@giordano
Copy link
Contributor

giordano commented Dec 1, 2024

Shouldn't this be in the LinearAlgebra repo?

@fredrikekre fredrikekre transferred this issue from JuliaLang/julia Dec 1, 2024
@stevengj
Copy link
Member

stevengj commented Dec 1, 2024

A non-breaking change could be to pass an additional argument, e.g. sqrt(A, Real) if you want a real result (throwing an exception if not real) and sqrt(A, Complex) if you want a complex result (even if the result is real).

Note that eigen (and eigvals and eigvecs) have the same issue — for a real matrix, they return real matrices/vectors if possible and complex matrices/vectors if not. So any change to sqrt should probably be mirrored there.

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

No branches or pull requests

4 participants