JuliaAstro / UnitfulAstro.jl

An extension of Unitful.jl for astronomers.
Other
22 stars 11 forks source link

Working in SI units #23

Closed md-arif-shaikh closed 3 years ago

md-arif-shaikh commented 3 years ago

Hi, I was wondering if there is a simple way to import all the astrophysical units only in SI units, i.e., all I want is the number. For example for the mass of the Sun, I want the value 1.989 x 1e30 and for speed of light, it would be 3 x 1e8 and similarly for other astrophysical constants.

mileslucas commented 3 years ago

Hi there! This kind of functionality already exists, and I'll also point you towards https://github.com/JuliaPhysics/PhysicalConstants.jl which has even more constants. By default those are defined in SI units. Here's an example of how to string these together for some calculations-

For getting preferred units, you'll leverage upreferred and Unitful.preferunits (both from Unitful.jl). By default upreferred is set for SI

julia> using Unitful, UnitfulAstro
julia> 1u"Msun" |> upreferred
1.988409870698051e30 kg

According to Unitful, in order to change preferred units you'll have to restart the runtime (i.e., you need to call preferunits before calling upreferred for the first time)

julia> using Unitful, UnitfulAstro
julia> Unitful.preferunits(u"cm,g,s"...) # cgs
julia> 1u"Msun" |> upreferred
1.988409870698051e33 g

For constants like the Stefan-Boltzmann constant, speed of light, Gravitational constant, etc.

julia> using PhysicalConstants.CODATA2018: G
julia> G
Newtonian constant of gravitation (G)
Value                         = 6.6743e-11 m³ kg⁻¹ s⁻²
Standard uncertainty          = 1.5e-15 m³ kg⁻¹ s⁻²
Relative standard uncertainty = 2.2e-5
Reference                     = CODATA 2018

julia> G |> upreferred
6.674299999999999e-8 cm³ g⁻¹ s⁻²

this example actually doesn't work currently but will as soon as https://github.com/PainterQubits/Unitful.jl/pull/431 is merged. Like I said, though, PhysicalConstants.jl is SI by default, and in the meantime you can add

julia> Unitful.upreferred(q::Unitful.AbstractQuantity) = uconvert(upreferred(unit(q)), q)

locally and it should all work!

mileslucas commented 3 years ago

I'm going to go ahead and close this issue- if you have further questions or have problems feel free to reopen!