# How do I use symbolic variables with Unitful?

I am trying to do some basic Physics problems using Julia. I have had some success using Unitful, but I do not know how I can solve problems for general parameters (i.e., get a closed form of the solution in terms of the missing variables).

E.g., I want to do something like:

``````force(m, a) = m*a

m = 10u"kg"
@symbol a # pseudocode
a = (a)u"m/s^2" # give it a unit
print(force(m, a))
``````

This should print `10*a N`. (`N` is Newton, defined by Unitful).

Of course, this example is trivial, but it is more interesting in bigger problems.

2 Likes

You need a CAS (Computer Algebra System) library to perform symbolic computations.
ModelingToolkit is such a library implemented in julia.

However ModelingToolkit does not implement multiplying a variable with a general Number but only with Real and Complex and unfortunately Unitful quantity are subtype of Number but not of Real:
I am not sure why this is the case: it looks like it could be a subtype of Real but there may be a good reason for this.

Also even if it worked it would not print 10 * a N. but something like (10 N)a

1 Like

I am starting to suspect whether Julia is a bad choice for this type of work, though SymPy does have some support (which does not seem to have good Julian wrappers). Do you know any good CASes that work with units?

I suggest openning an issue on Symbolics.jl
which is now the CAS behind ModellingToolkit, as of this week.

2 Likes
1 Like

@NightMachinary you can try as explained in the github issue:

``````julia> using Unitful

julia> using ModelingToolkit

julia> import Base:*

julia> *(x::Unitful.AbstractQuantity,y::Num) =  Quantity(x.val*y, unit(x))
* (generic function with 735 methods)

julia> *(y::Num,x::Unitful.AbstractQuantity) = x*y
* (generic function with 736 methods)

julia> @variables var_a
(var_a,)

julia> force(m,a)=m*a
force (generic function with 1 method)

julia> a=var_a*u"m/s^2"
var_a m s^-2

julia> m=10u"kg"
10 kg

julia> force(m,a)
10var_a kg m s^-2
``````
1 Like

I am now using SymPy, and it somewhat works out of the box.

https://frinklang.org/ is a language that does a lot of units stuff and some algebra.

1 Like

It seems closed source though. Wouldn’t Mathematica be a much better option then?