Skip to content

Instantly share code, notes, and snippets.

@Miladiouss
Last active April 13, 2022 22:27
Show Gist options
  • Select an option

  • Save Miladiouss/fb06d9e08efdb24f8c8a45c8b6fea503 to your computer and use it in GitHub Desktop.

Select an option

Save Miladiouss/fb06d9e08efdb24f8c8a45c8b6fea503 to your computer and use it in GitHub Desktop.
Proper way of constructing and displaying quantities using Astropy in Jupyter Notebooks
# Science
from astropy.units import Unit
import numpy as np
# Notebook
from IPython.display import Markdown
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
# Handy functions
def Qshow(Q, sigfig=2, unit=None):
if unit is not None:
Q = Q.to(unit)
Q = Q.round(sigfig - int(np.log10(Q.value)))
if Q.info.name is not None:
output = Markdown(f'{Q.info.name} = {Q._repr_latex_()}')
else:
output = Markdown(f'{Q._repr_latex_()}')
return output
# Parameter
density = 2 * Unit('g/cm^3')
density.info.name = r'$\rho$'
Qshow(density)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment