[AstroPy] Design Pattern
Russell Osterlund
russellosterlund at gmail.com
Tue Jun 27 09:54:53 EDT 2017
Thank you!
Your 1st example clarifies things - In order to make my first attempt work
correctly, I need to call the "to" method with the correct units on the
constant G!
All the best.
Russ Osterlund
On Mon, Jun 26, 2017 at 7:39 PM, Derek Homeier <
derek at astro.physik.uni-goettingen.de> wrote:
> 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
>
> _______________________________________________
> AstroPy mailing list
> AstroPy at python.org
> https://mail.python.org/mailman/listinfo/astropy
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/astropy/attachments/20170627/34877732/attachment.html>
More information about the AstroPy
mailing list