Keno / SIUnits.jl

Efficient unit-checked computation
Other
70 stars 26 forks source link

abs2 is not defined for SIQuantity #110

Open rawlik opened 7 years ago

rawlik commented 7 years ago
julia> abs2(1Volt)
ERROR: MethodError: no method matching abs2(::SIUnits.SIQuantity{Int64,2,1,-3,-1,0,0,0,0,0})
Closest candidates are:
  abs2(::Bool) at bool.jl:38
  abs2(::Measurements.Measurement{T<:AbstractFloat}) at /Users/rawlik/.julia/v0.5/Measurements/src/math.jl:610
  abs2(::Real) at number.jl:41
  ...

julia> abs(1Volt)^2
1 kg²m⁴s⁻⁶A⁻²

It would be very interesting if this would work, as then one can propagate units through linear fits:

julia> x = (1:10)Ampere
       y = randn(10)Volt
       [x ones(x)] \ y
ERROR: MethodError: no method matching abs2(::SIUnits.SIQuantity{Float64,0,0,0,1,0,0,0,0,0})
Closest candidates are:
  abs2(::Bool) at bool.jl:38
  abs2(::Measurements.Measurement{T<:AbstractFloat}) at /Users/rawlik/.julia/v0.5/Measurements/src/math.jl:610
  abs2(::Real) at number.jl:41
tomasaschan commented 7 years ago

It should be very easy to define a fallback as abs2(x::SIQuantity) = abs(x)^2, but a more efficient implementation is probably something like

function abs2{T,m,kg,s,A,K,mol,cd,rad,sr}(x::SIQuantity{T,m,kg,s,A,K,mol,cd,rad,sr})
    val = abs2(x.val)
    SIQuantity{typeof(val),2*m,2*kg,2*s,2*A,2*K,2*mol,2*cd,2*rad,2*sr}(val)
end

A PR with this (and a couple of tests) would most likely get merged in no time ;)