1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Store derived units without prefix while avoiding unit to base

Discussão em 'Python' iniciado por Stack, Outubro 3, 2024 às 15:12.

  1. Stack

    Stack Membro Participativo

    I am new to Pint. I am dealing with derived units such as Siemens, Joule, Farad etc. In particular, I would like to store the created quantities with their units without any prefix, without converting to the base units. For example, 1 millisiemens (mS) should be stored as 0.001 S.

    Let's try to explain this with an example. The following code snippet:

    import pint

    ureg = pint.UnitRegistry(system="mks")
    quantity = ureg.Quantity(1, ureg.Unit("mm")) # Define quantity of 1 millimiter
    stored_quantity = quantity.to_base_units()
    print(stored_quantity) # print: 0.001 meter OK


    In this case, I get the desired effect, the quantity stored is in meter. But when I try with derived quantities, Pint converts it to the base units, or (using others to_xxx method) it preserves the derived quantity but also the prefix. Let's see with an example:

    quantity = ureg.Quantity(1, ureg.Unit("mJ"))
    print(quantity) # 1 millijoule
    print(quantity.to_root_units()) # 1.0 gram * meter ** 2 / second ** 2
    print(quantity.to_base_units()) # 0.001 kilogram * meter ** 2 / second ** 2
    print(quantity.to_reduced_units()) # 1 millijoule -> Preserves derived unit but also "milli"
    print(quantity.to_compact()) # 1 millijoule -> Preserves derived unit but also "milli"


    The desired output should be 0.001 J.

    Of course, one could explicitly call:

    stored_quantity = quantity.to(ureg.joule),

    but I couldn't find a way to get the information of ureg.joule programmatically. Is there a way to achieve this goal?

    Continue reading...

Compartilhe esta Página