Showing posts with label unit converter. Show all posts
Showing posts with label unit converter. Show all posts

Unit converter

For energy engineers, unit conversion is the most basic of basics. In the field, there are gauge units and absolute units, so minor mistakes can lead to very different calculation results. Also, there are times when you want to verify your unit conversion.

Python code of unit converter


The Python code below is an example of temperature and pressure engineering unit conversion.
dbUnit = [
         ['C', 'Temperature', 1.0, 0.0],
         ['K', 'Temperature', 1.0, 273.15],
         ['F', 'Temperature', 1.8, 32.0],
         ['R', 'Temperature', 1.8, 491.67],
         ['kPa', 'Pressure',  1.0, 0.0],
         ['MPa', 'Pressure',  0.001, 0.0],
         ['bar', 'Pressure',  0.01, 0.0],
         ['N/m2', 'Pressure', 1000.0, 0.0],
         ['atm', 'Pressure', 0.009869233, 0.0],
         ['at', 'Pressure', 0.01019716, 0.0],
         ['kg/cm2', 'Pressure', 0.01019716, 0.0],
         ['psia', 'Pressure', 0.1450377, 0.0],
         ['lbf/ft2', 'Pressure', 20.88543, 0.0],
         ['torr', 'Pressure', 7.500615, 0.0],
         ['kPag', 'Pressure', 1.0, -101.325],
         ['MPag', 'Pressure', 0.001, -0.101325],
         ['bar_g', 'Pressure', 0.01, -1.01325],
         ['N/m2_g', 'Pressure', 1000.0, -101325.0],
         ['atm_g', 'Pressure', 0.009869, -1.0],
         ['ate', 'Pressure', 0.01019716, -1.033227],
         ['kg/cm2_g', 'Pressure', 0.01019716, -1.033227],
         ['psig', 'Pressure', 0.1450377, -14.696],
         ['lbf/ft2_g', 'Pressure', 20.88543, -2116.216],
         ['torr_g', 'Pressure', 7.500615, -760.0],
         ]


def loadUnit(search):
    for i in range(len(dbUnit)):
        if dbUnit[i][0] == search:
            UnitGroup = dbUnit[i][1]
            UnitScale = float(dbUnit[i][2])
            UnitOffset = float(dbUnit[i][3])

    return UnitGroup, UnitScale , UnitOffset

def unitconv(number, Unit_old, Unit_new):
    
    Group_old, Scale_old, Offset_old = loadUnit(Unit_old)
    Group_new, Scale_new, Offset_new = loadUnit(Unit_new)

    if Scale_old == 0 or Group_old != Group_new: 
        return None

    return ((number - Offset_old) / Scale_old) * Scale_new + Offset_new

print(unitconv(50, "C", "R")) # 50 C = 581.67 R
print(unitconv(10, "bar_g", "kPa")) # 10 bar_g = 1101.325 kPA