Skip to content

Commit

Permalink
Modify cross product to be consistent with StaticArrays.jl
Browse files Browse the repository at this point in the history
  • Loading branch information
KeitaNakamura committed Oct 16, 2024
1 parent b516b8c commit 2a7a3f7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 23 deletions.
16 changes: 5 additions & 11 deletions src/ops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -444,15 +444,11 @@ end
end

"""
cross(x::Vec{3}, y::Vec{3}) -> Vec{3}
cross(x::Vec{2}, y::Vec{2}) -> Vec{3}
cross(x::Vec{1}, y::Vec{1}) -> Vec{3}
cross(x::Vec, y::Vec)
x × y
Compute the cross product between two vectors.
The vectors are expanded to 3D frist for dimensions 1 and 2.
The infix operator `×` (written `\\times`) can also be used.
`x × y` (where `×` can be typed by `\\times<tab>`) is a synonym for `cross(x, y)`.
The infix operation `x × y` (where `×` can be typed by `\\times<tab>`) is a synonym for `cross(x, y)`.
# Examples
```jldoctest
Expand All @@ -475,16 +471,14 @@ julia> x × y
-0.37588028973385323
```
"""
@inline cross(x::Vec{1, T1}, y::Vec{1, T2}) where {T1, T2} = zero(Vec{3, promote_type(T1, T2)})
@inline function cross(x::Vec{2, T1}, y::Vec{2, T2}) where {T1, T2}
z = zero(promote_type(T1, T2))
@inbounds Vec(z, z, x[1]*y[2] - x[2]*y[1])
end
@inline function cross(x::Vec{3}, y::Vec{3})
@inbounds Vec(x[2]*y[3] - x[3]*y[2],
x[3]*y[1] - x[1]*y[3],
x[1]*y[2] - x[2]*y[1])
end
@inline function cross(x::Vec{2}, y::Vec{2})
@inbounds x[1]*y[2] - x[2]*y[1]
end

# power
@inline Base.literal_pow(::typeof(^), x::AbstractSquareTensor, ::Val{-1}) = inv(x)
Expand Down
15 changes: 3 additions & 12 deletions test/ops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -203,21 +203,12 @@ end
end
end
@testset "cross" begin
for T in (Float32, Float64), dim in 1:3
for T in (Float32, Float64), dim in 2:3
x = rand(Vec{dim, T})
y = rand(Vec{dim, T})
@test (@inferred x × x)::Vec{3, T} zero(Vec{3, T})
@test x × y -y × x
if dim == 2
a = Vec{2, T}(1,0)
b = Vec{2, T}(0,1)
@test (@inferred a × b)::Vec{3, T} Vec{3, T}(0,0,1)
end
if dim == 3
a = Vec{3, T}(1,0,0)
b = Vec{3, T}(0,1,0)
@test (@inferred a × b)::Vec{3, T} Vec{3, T}(0,0,1)
end
dim == 2 && @test (@inferred x × x)::T zero(T)
dim == 3 && @test (@inferred x × x)::Vec{3, T} zero(Vec{3, T})
end
end
@testset "pow" begin
Expand Down

0 comments on commit 2a7a3f7

Please sign in to comment.