Skip to content

Commit 3d778b6

Browse files
authored
Fix * for numbers with non-commutative multiplication (#608)
1 parent c9f6386 commit 3d778b6

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/quantities.jl

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,11 @@ Quantity(x::Number, y::Units{()}) = x
2929
*(x::AbstractQuantity, y::Units, z::Units...) = Quantity(x.val, *(unit(x),y,z...))
3030
*(x::AbstractQuantity, y::AbstractQuantity) = Quantity(x.val*y.val, unit(x)*unit(y))
3131

32-
*(y::Number, x::AbstractQuantity) = *(x,y)
32+
function *(x::Number, y::AbstractQuantity)
33+
y isa AffineQuantity &&
34+
throw(AffineError("an invalid operation was attempted with affine quantities: $x*$y"))
35+
return Quantity(x*y.val, unit(y))
36+
end
3337
function *(x::AbstractQuantity, y::Number)
3438
x isa AffineQuantity &&
3539
throw(AffineError("an invalid operation was attempted with affine quantities: $x*$y"))

test/runtests.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,13 @@ end
522522
@test isa(1m^3/s, VolumeFlow)
523523
end
524524

525+
# A number type with non-commutative multiplication
526+
struct MatNum <: Number
527+
mat::Matrix{Int}
528+
end
529+
Base.:(==)(x::MatNum, y::MatNum) = x.mat == y.mat
530+
Base.:*(x::MatNum, y::MatNum) = MatNum(x.mat*y.mat)
531+
525532
@testset "Mathematics" begin
526533
@testset "> Comparisons" begin
527534
# make sure we are just picking one of the arguments, without surprising conversions
@@ -604,6 +611,9 @@ end
604611
@test @inferred((NaN*kg)*false) === 0.0kg # `false` acts as "strong zero"
605612
@test @inferred(false*(-Inf*kg)) === -0.0kg # `false` acts as "strong zero"
606613
@test typeof(one(eltype([1.0s, 1kg]))) <: Float64 # issue 159, multiplicative identity
614+
# Multiplicaton can be non-commutative
615+
@test Quantity(MatNum([1 2; 3 4]), m) * MatNum([5 6; 7 8]) == Quantity(MatNum([19 22; 43 50]), m)
616+
@test MatNum([5 6; 7 8]) * Quantity(MatNum([1 2; 3 4]), m) == Quantity(MatNum([23 34; 31 46]), m)
607617
end
608618
@testset "> Division" begin
609619
@test 360° / 2 === 180.0° # Issue 110

0 commit comments

Comments
 (0)