Unitful arguments to functions?

Hi,

just started using Unitful.jl, and it looks great. I wanted to define a function that takes, as a first argument, some length, and as second argument something inverse length. First one is no problem, but despite trying all variations that came to my mind and looking for info in the Unitful documentation, I didn’t find how to do it. So, ideally I would like to do something like:

f1(a::Unitful.Length, b::Unitful.Length^-1) = […]

but I don’t seem to get the syntax right for the second argument.

Any help appreciated,

i had this laying around

function f1(a::Unitful.Quantity{<:Real, Unitful.𝐋^1}, b::Unitful.Quantity{<:Real, Unitful.𝐋^(-1)})
return 0 
end

if you want more ease of writing, you can use a type const:

const INV_LENGTH = Unitful.Quantity{<:Real, Unitful.𝐋^(-1)}
function f1(a::Unitful.Length, b:INV_LENGTH)
return 0 
end
1 Like

The relevant part of the manual is at
https://painterqubits.github.io/Unitful.jl/stable/newunits/#Unitful.@derived_dimension

You use the @derived_dimension macro.

@derived_dimension InvLength 𝐋^-1
or
@derived_dimension InvLength dimension(u"1/m")

Then your function would be f1(a::Unitful.Length, b::InvLength) = ...

6 Likes

Many thanks to both.

@derived_dimension InvLength dimension(u"1/m") works very nice and easy on the eyes.

Cheers,

1 Like

And is it possible to round the result to a given number of digits? The following doesn’t work


round(656.1122u"nm",digits=2)

and something like this works but probably there is a better way…


round_uful(uful,digs) = round(ustrip(uful),digits=digs) * unit(uful)
julia> round(u"nm", 656.1122u"nm", digits=2)
656.11 nm
1 Like

Many thanks