Skip to content

Commit

Permalink
Fix log for negative quaternions (#115)
Browse files Browse the repository at this point in the history
* Add log tests

* Add more general failing test

* Fix implementation of log for negative quat
  • Loading branch information
sethaxen authored Dec 7, 2022
1 parent bdf34b9 commit 3ab59a0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/Quaternion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -259,12 +259,19 @@ for f in (@static(VERSION ≥ v"1.6" ? (:sincos, :sincospi) : (:sincos,)))
end
end

# this implementation is roughly 2x as fast as extend_analytic(log, q)
function Base.log(q::Quaternion)
a = abs(q)
M = abs_imag(q)
theta = atan(M, q.s)
scale = theta / ifelse(iszero(M), oneunit(M), M)
return Quaternion(log(a), q.v1 * scale, q.v2 * scale, q.v3 * scale)
a = abs_imag(q)
theta = atan(a, q.s)
scale = theta / a
if a > 0
return Quaternion(log(abs(q)), scale * q.v1, scale * q.v2, scale * q.v3)
else
# q == real(q), so f(real(q)) may be real or complex.
# we choose to embed complex numbers in the quaternions by identifying the first
# imaginary quaternion basis with the complex imaginary basis.
return Quaternion(log(abs(q.s)), oftype(scale, theta), zero(scale), zero(scale))
end
end

Base.:^(q::Quaternion, w::Quaternion) = exp(w * log(q))
Expand Down
5 changes: 5 additions & 0 deletions test/Quaternion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,11 @@ end
@testset "additional properties" begin
@testset "log" begin
@test log(zero(QuaternionF64)) === Quaternion(-Inf, 0, 0, 0)
@test log(one(QuaternionF64)) === Quaternion(0.0, 0, 0, 0)
@test log(-one(QuaternionF64)) == Quaternion(0.0, π, 0, 0)
x = rand()
@test log(quat(x)) == quat(log(x))
@test log(quat(-x)) == Quaternion(reim(log(complex(-x)))..., 0, 0)
end

@testset "exp" begin
Expand Down

0 comments on commit 3ab59a0

Please sign in to comment.