[AstroPy] Design Pattern

Derek Homeier derek at astro.physik.uni-goettingen.de
Mon Jun 26 19:39:46 EDT 2017


On 27 Jun 2017, at 12:37 am, Russell Osterlund <russellosterlund at gmail.com> wrote:
> 
> When I execute the following:
> 
> print( 'v:', np.sqrt( ( G * u.M_sun.to( u.kilogram ) ) / u.au.to( u.meter ) ) / 1000 )
> 
> this is the output:
> 
> v: 29.788833564362875 m(3/2) / (kg(1/2) s)
> 
> But when I change the code to this:
> 
> print( 'v:', np.sqrt( ( ( G * u.M_sun ) / u.au ) ).to( u.km / u.second ) )
> 
> I see this:
> 
> v: 29.788833564362875 km / s
> 
> The differing output suggests that the correct design pattern is to work with the constants as-is and only convert using the "to" method when required, e.g., np.sqrt(), or displaying output. Is this correct?
> 
The difference is that the constant G is a Quantity as opposed to the units M_sun, au.
When using constants and Quantities throughout, both ways should work:

import astropy.constants as apc
import astropy.units as apu

print('v={0:}'.format(np.sqrt(apc.G.to('km3/(kg s2)')*apc.M_sun.to('kg')/(1*apu.au).to('km'))))
v=29.788833564362875 km / s

print(‘v = {0:.3f}'.format(np.sqrt(apc.G*apc.M_sun/(1*apu.au)).to('km/s')))
v = 29.789 km / s

May not seem too intuitive, and I can’t actually tell you the reasoning why it is behaving
this way, but as the unit is just an attribute of a Quantity, there probably is one…

HTH,
					Derek



More information about the AstroPy mailing list