Unitful.jl icon indicating copy to clipboard operation
Unitful.jl copied to clipboard

How do I use symbolic variables with Unitful?

Open NightMachinery opened this issue 3 years ago • 2 comments

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.

Also posted to the discourse.

NightMachinery avatar Mar 03 '21 16:03 NightMachinery

Unitful isn't really a library to do symbolic algebra, simply a library to express units. However, if you'd like to instead solve/express stuff like this in a way a regression tool of some sort could solve, you could certainly just set up a lambda expression:

force(m, a) = m*a

m = 10u"kg"
force_equation = a -> force(m, a*u"m/s^2")

If you really want a symbolic algebra system, there certainly are symbolic algebra systems for Julia, though I haven't used any of them much; Symbolics.jl is one If you want any compatibility between these packages and Unitful, though, you'll likely have to implement it yourself; it would probably need to sit on the side of the symbolic algebra package, as that package would have to understand how to deal with units in expressions.

lukebemish avatar Dec 06 '21 03:12 lukebemish

Here is some code using Symbolics,Plots, PlutoUI,Latexify,Unitful,UnitfulLatexify

let
	@variables Work, heat,junit,weight, g,h,n,x
	heat=(2.00*10^6)u"cal"
	junit=4.186u"J/cal"
	g=9.80u"m/s^2"
	weight=50u"kg"
	h=2u"m"
	Work=heat*junit
        n=Work/(weight*g*h)
       latexify(:(n=Work/(weight*g*h)=$n))
end
let
	
	heat,g, j,weight,height=(2.00*10^6)u"cal",9.82u"m/s^2",4.186u"J/cal",50u"kg",2u"m"

	latexify([heat,g, j,weight,height])
end
let
	a = 9.82u"m/s^2"
        t = 4u"s"
        x = a*t^2
       latexify(:(x = a*t^2 = $x))
end

phpsmarter avatar Jul 24 '22 09:07 phpsmarter