Unitful.jl - how to represent "particles per cubic centimeter"

Using this equation, I’d like to create a function to calculate the velocity of the Solar Wind.

The equation has three inputs: mp (the mass of a photon), n (number of particles per cubic cm), and V (velocity in kilometers per second).

I’d like to use Unitful.jl to type the arguments. For example, I’m using the following to type Velocity:


The mass of photon is easy to represent, in fact there’s a Unitful constant for it.

What I can’t figure out is how to represent n, the number of particles per cm^3.

Unitful defines an “amount” dimension, 𝐍 (\bfN), but you don’t appear to be able to use it in units, so I can’t say 7u"𝐍/cm^3". There don’t appear to be any amount unit types other than moles, which doesn’t seem like the right choice.

I tried defining a new unit, but using the macros to do so in Pluto doesn’t work.

I’d prefer to type the variable with Unitful because, I think, you get conversions for free. So, for example, if the inputs were particles per cubic meter they’d automatically be converted.

I’d be grateful for some help! Thanks in advance.

Presumably this is a flaw in Pluto and not Unitful.jl. You could just eval the definition in, or put it in a separate file and include that file.

This trouble with macros in Pluto.jl will hopefully be addressed soon once Analyse macros by Pangoraw · Pull Request #1032 · fonsp/Pluto.jl · GitHub is merged.

Okay, I just checked in a Pluto notebook, and defining the unit in a module and then registering that module seems to work for me:

### A Pluto.jl notebook ###
# v0.14.7

using Markdown
using InteractiveUtils

# ╔═╡ 2784b1a6-c274-11eb-1408-b1cfb6b90eec
using Unitful

# ╔═╡ ad245d53-7925-48e3-bfbd-f86c0219e3bf
module MyUnits 
using Unitful
@unit N "N" Number 1 false

# ╔═╡ e6cf3bc1-f1bb-4cf4-8335-a28938ebb1ac

# ╔═╡ 6d64e53c-fd95-4202-b313-8ee0da6a7fef

# ╔═╡ Cell order:
# ╠═2784b1a6-c274-11eb-1408-b1cfb6b90eec
# ╠═ad245d53-7925-48e3-bfbd-f86c0219e3bf
# ╠═e6cf3bc1-f1bb-4cf4-8335-a28938ebb1ac
# ╠═6d64e53c-fd95-4202-b313-8ee0da6a7fef

I’m not that familiar with Unitful.jl, but wouldn’t you just use the units 1/cm^3 or cm^(-3)?


@Mason - Ah, very interesting! I had tried to create a unit that way, but not in a module. Thank you!

@DNF - Very elegant and, I bet, what the authors had in mind. It seems to work. I’ll fiddle with it a bit more to confirm that there aren’t side effects. Love that your intuition took you right to the answer!

1 Like

A postscript for people who find this in the future:

If you have created a variable with units like this:

n = 7u"cm^-3"

And, later, you want to get the 7 out, you can strip the units by using the multiplicative inverse of the units:

n*u"cm^3" == 7 # true

Or use the ustrip function.