So, I’ve used Unitful a little bit and I like the library, but there is one oddity I’ve noticed with the Moriarty unit, at least in v1.11.0. If you enter this…
1u"mol/L" * 20u"L"
OK, that’s what I expect, good, but…
1u"M" * 20u"L"
20 L M
This doesn’t seem like correct behavior, especially since the Molarity unit was defined in pkgdefaults.jl as:
@unit M “M” Molar 1mol/L true true
Am I missing something here? I tried looking about for if this was an issue, but didn’t find anything. Maybe I wasn’t looking in the right place? Maybe this is expected behavior and I’m not understanding something? Or maybe this is a bug and I should report it?
Sorry, So many questions! OOPS ALL QUESTIONS
I think there is nothing wrong, but that the capacity of simplifying units automatically of the package is somewhat limited (also because it is hard to say what the user wants). For instance:
julia> 1u"mol/L" * 20u"L"
julia> 1u"M" * 20u"L"
20 L M
julia> 1u"N" * 1u"m"
1 m N
julia> uconvert(u"J", 1u"m*N")
These are two similar situations where we could expect simpler units to be displayed. But is that what the user wants? Sometimes yes, but hard to say.
At least we can use explicit checks with the units:
julia> 1u"J" == 1u"N*m"
julia> 1u"M*L" == 1u"mol"
To add to the previous answer:
1u"M" * 20u"L" is an intermediate result - just use it as is for the following computations. For the final result you may use
uconvert to transform to your desirable form, or just do
julia> 1u"M" * 20u"L" |> upreferred
As others have said, there is no simplification of units performed, but you can force conversions. For my uses, uprefferred isn’t great, because it boils everything down to the base units, and often you want something non-base, like Watts instead of kg m^2 s^-3. So I make use of piping ( |> bakes out to a form of uconvert) a lot to make an aesthetic and clean output.
julia> 60.0u"mi/hr" * 5.0u"minute"
300.0 mi minute hr^-1
julia> 60.0u"mi/hr" * 5.0u"minute" |> u"mi"
Also, it took me a while to find DefaultSymbols, but i tend to use that a lot (though it does drop a lot of names in your workspace, which can conflict, especially if you use some 1-2 letter variable names). The u" " make the variables pop visually more, but the syntax is easier to follow sometimes without them.
julia> 5.0W/m^2 * (1.0cm)^2 |> mW
just be careful with angles, since they are not preserved on conversion.
Oh boy, this has been useful. Thanks @lmiq,@Eben60, and @DanDeepPhase for the OOPS ALL ANSWERS.
I mean really, you all added something useful for me. It’s been awhile since I worked with physics calculations, so it’s a good reminder that you might not always want to break units down. It’s also good to know that upreferred is there if that’s what you want.
You know, like so…
julia> 1u"N" * 20u"m" |> upreferred
20 kg m^2 s^-2
I’ll have to check out that function a bit more, and the DefaultSymbols module. Thanks again!