pythonmathexp

math.exp() is returning 0 for floats


I've included the relevant code for my issue. When I run the code my feet to meters function works as expected. -M*g*z/(T*R) inside of the math.exp() operation gives a negative float of decent size. Despite this, my function Pressure() returns only 0.0, like this: z = 1000 ft, P = 0.0 atm. What am I doing wrong? I've made sure everything is a float so I don't get truncation, but I am still having issues. Any response would be appreciated! Thanks!

def Pressure(z):
    Po=1.0 #atm
    M=29.0 #kg/kmol
    g=9.81 #m/s^2
    T=300.0 #K
    R=0.082057 #Latm/molK
    return math.exp(-M*g*z/(T*R))

def ft_to_m(x):
    return float(3.28084*x)

for i in range(0,30001): #i in ft
    if i % 1000 == 0:
        print("z =",i,"ft, P =",Pressure(ft_to_m(i)), "atm") 
    continue

Solution

  • I don't know whether it's your formula (-M*g*z/(T*R)) that's wrong or you're misunderstanding math.exp: math.exp(x) is ex.

    Here your x (the result of your formula) is already -37915 at the first step and it only goes downhill from there. e-38000 is pretty much a complex way to write 0 since Python uses mere 64-bit floating-point integers.

    edit: looks to be your formula: M = 29 g / kmol (or worse lb/lb-mol) not kg/kmol, you may also want to check your values for R and K.

    Basically review all your values, then do a dimensional analysis to ensure the units fit together (it doesn't help that you're using non-SI units like atm so "standard" list of constants for the barometric formula don't apply as-is).