Skip to content

Commit

Permalink
Fix * for numbers with non-commutative multiplication (#608)
Browse files Browse the repository at this point in the history
  • Loading branch information
sostock authored Feb 8, 2023
1 parent c9f6386 commit 3d778b6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/quantities.jl
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ Quantity(x::Number, y::Units{()}) = x
*(x::AbstractQuantity, y::Units, z::Units...) = Quantity(x.val, *(unit(x),y,z...))
*(x::AbstractQuantity, y::AbstractQuantity) = Quantity(x.val*y.val, unit(x)*unit(y))

*(y::Number, x::AbstractQuantity) = *(x,y)
function *(x::Number, y::AbstractQuantity)
y isa AffineQuantity &&
throw(AffineError("an invalid operation was attempted with affine quantities: $x*$y"))
return Quantity(x*y.val, unit(y))
end
function *(x::AbstractQuantity, y::Number)
x isa AffineQuantity &&
throw(AffineError("an invalid operation was attempted with affine quantities: $x*$y"))
Expand Down
10 changes: 10 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,13 @@ end
@test isa(1m^3/s, VolumeFlow)
end

# A number type with non-commutative multiplication
struct MatNum <: Number
mat::Matrix{Int}
end
Base.:(==)(x::MatNum, y::MatNum) = x.mat == y.mat
Base.:*(x::MatNum, y::MatNum) = MatNum(x.mat*y.mat)

@testset "Mathematics" begin
@testset "> Comparisons" begin
# make sure we are just picking one of the arguments, without surprising conversions
Expand Down Expand Up @@ -604,6 +611,9 @@ end
@test @inferred((NaN*kg)*false) === 0.0kg # `false` acts as "strong zero"
@test @inferred(false*(-Inf*kg)) === -0.0kg # `false` acts as "strong zero"
@test typeof(one(eltype([1.0s, 1kg]))) <: Float64 # issue 159, multiplicative identity
# Multiplicaton can be non-commutative
@test Quantity(MatNum([1 2; 3 4]), m) * MatNum([5 6; 7 8]) == Quantity(MatNum([19 22; 43 50]), m)
@test MatNum([5 6; 7 8]) * Quantity(MatNum([1 2; 3 4]), m) == Quantity(MatNum([23 34; 31 46]), m)
end
@testset "> Division" begin
@test 360° / 2 === 180.0° # Issue 110
Expand Down

0 comments on commit 3d778b6

Please sign in to comment.