Unitful.jl icon indicating copy to clipboard operation
Unitful.jl copied to clipboard

Convert "Hz" to "1/s"

Open ruizhi92 opened this issue 3 years ago • 4 comments

Hello,

I'm able to convert "1/s" to "Hz", however not able to convert "Hz" to "1/s". Is this as expected? It seems suspicious since example in the doc shows one can convert between "J" and "N*m" in both ways.

julia> uconvert(u"Hz", 1u"1/s")
julia> 1 Hz

julia> uconvert(u"1/s", 1u"Hz")
julia> MethodError: no method matching uconvert(::Quantity{Int64, 𝐓^-1, Unitful.FreeUnits{(s^-1,), 𝐓^-1, nothing}}, ::Quantity{Int64, 𝐓^-1, Unitful.FreeUnits{(Hz,), 𝐓^-1, nothing}})

Thanks.

ruizhi92 avatar Dec 08 '21 06:12 ruizhi92

The problem is that u"1/s" is a quantity, not a unit. You can use u"s^-1" instead:

julia> typeof(u"1/s")
Quantity{Int64, 𝐓 ^-1, Unitful.FreeUnits{(s^-1,), 𝐓 ^-1, nothing}}

julia> typeof(u"s^-1")
Unitful.FreeUnits{(s^-1,), 𝐓 ^-1, nothing}

julia> uconvert(u"s^-1", 1u"Hz")
1 s^-1

Maybe the fact that 1/unit creates a quantity should be documented.

sostock avatar Dec 08 '21 06:12 sostock

@sostock Thank you for the nice and clean explanation

ruizhi92 avatar Dec 08 '21 07:12 ruizhi92

I was also surprised that "Hz" and "s" don't "annihilate" ... Is there a function to reduce units For example:

julia> 0.01u"m" / 5u"m"
0.002

julia> 1u"cm" / 5u"m"
0.2 cm m^-1

How can I collect the similar units in the second expression to get the scalar returned by the first expression?

hros avatar Dec 17 '22 20:12 hros

You can use upreferred for that:

julia> 1u"cm" / 5u"m"
0.2 cm m^-1

julia> upreferred(ans)
0.002

sostock avatar Dec 18 '22 13:12 sostock