Search code examples
pythonnumpyastropy

How to take log of a unit with dimensions?


I have a temperature variable with Kelvin units. I need to take log10 of it with np.log10, but it does not work if a number has dimensions. What is the easiest way to remove dimensions from the variable so I can take a log of it?

Example

import astropy.units as u
import numpy as np

temp = 6000 * u.K
np.log10(temp)

Shows the error message:

UnitTypeError: Can only apply 'log10' function to dimensionless quantities

Solution

  • You can either drop dimension with .value:

    >>> np.log10(temp.value)
    3.7781512503836434
    

    Or divide by u.K to make it dimensionless:

    >>> np.log10(temp / u.K)
    <Quantity 3.7781512503836434>