Nam's Space Library

[Astropy] Units conversion

First, we need to install it using pip

Just simply type ‘pip install astropy’ in the terminal to install it

The Astropy module includes many constants commonly used in space, so you don’t need to specify them separately when coding!

For example, the well-known gravitational constant value is:

 

G=6.67×10−11 N⋅m^2/kg^2

Previously, to use this value, we would have to declare a variable and assign the value. Now, there’s no need to do that anymore! Let’s find it using Astropy!

 

The first line means we’re going to import constants from astropy and name it ‘consts'. In the second line, we’re fetching the value of G among the many constants, and by running it, you’ll get the name, value, uncertainty, and unit all displayed.

This time, I fetched the value for a parsec. In this way, you can conveniently include any constant value you need such as speed of light

Also, in Astropy, you can change units! For example, let’s look at the speed of light.

The unit is displayed as m/s. Let’s convert it to a more complex unit, like km/yr.

Although, to be honest, there’s no practical reason to express the speed of light in km/year. But it’s still interesting!

As those who study physics know, units are very important, especially in calculations. Here, you can perform calculations with units included, and it adjusts for different units!

Let’s look at an example:

                                                                                                                            b=17.5km/s


                                                                                                                                                                                                                                                                     



and let b c
=ab=42m17.5km/s=42m17.5×103m/s=0.0024s

You have to convert km to m to calculate it

Now, let’s do this in coding!

Think of units as connected through multiplication and connect the units using multiplication symbols. Since we decided to use u for units, you need to prefix the desired unit with u

decompose means ‘to break down,’ so you can understand it as ‘calculating and breaking it down as much as possible.’

You can also create new units! For example, in baseball games, speed is often measured in km/h. In the U.S., they use mph (miles per hour).

It’s possible to define it this way too Creating frequently used units like this can be handy!

kph = u.def_unit(‘kph’, u.km / u.h)


That is all for today, Let’s take it step by step!

Scroll to Top