Represent dimensions with primes

I use Unitful in every single project so this is not to suggest that there is any kind of inadequacy! More of just a thought exercise. I was wondering if there would be any benefit if the different core dimensions were represented under the hood by unique primes and then any division could be performed with rational // division. The derived dimensions would then be multiples of primes and/or rational expressions of primes and/or multiples of those primes. It seems this would make keeping track of and simplifying units simpler and maybe faster?

Obviously everything is working fine! Just wanted to throw this out there and see what people think.

1 Like

it would simplify everything … maybe too much, some problems like to keep a specific (set of) derived units because their interrelationships, while simplifiable make sense themselves in the problem domain. If that is not a concern, then its worth mocking up and seeing how it goes.

This is a fun exercise in using simple types and overloading.

Step 0: write some functions to help generate prime numbers:

function isprime(num::Integer)
    if num <= 0
        return false
    end
    for j = 2:round(Int64, sqrt(num), RoundDown)
        if (num % j) == 0
            return false
        end
    end
    return true
end

ListOfPrimesUpTo(n) = filter(x -> isprime(x), 1:n)

Step 1: define a simple type structure to keep track of dimensions:

@enum DimensionPrimes begin
    Length        = 2
    Mass          = 3
    Time          = 5
    Current       = 7
    Temperature   = 11
    Luminosity    = 13
end

Step 2: overload a few methods to help things work:

Base.inv(a::DimensionPrimes) = 1//Integer(a)

Base.:*(a::DimensionPrimes, b::DimensionPrimes) = Integer(a)*Integer(b)

Base.:^(a::DimensionPrimes, b::Integer) = Integer(a)^b

Step 3: “test”:

# Short-form of dimension variables:
julia> L = Length; M = Mass; T = Time;

julia> Force = M*L*T^-2
6//25
1 Like

Interesting. I’d messed around a little bit and found that indeed kinetic energy ended up with the same rational expression as potential energy. Your little demo with overloading the base operators has been very instructional for me, thanks!

1 Like