I'm a beginning programmer, and I'm trying to find the root of an equation by using Newton's method. The value keeps returning 0 however, which results in a 'ZeroDivisionError: float division by zero' in 'self.β_func'. I'm trying to find the x-value in which p_max_T = p_max, which is why I've subtracted them from each other in beta_func.
It concerns the following piece of code:
import math
import scipy.optimize
P_1 = 1.22E-3
P_2 = 1.3E-3
T_P1 = 285
T_P2 = 288
T_AP = (1 / T_P1 - 1 / T_P2)**(-1) * math.log(P_2 / P_1)
T_APH = 25924
T_APL = 27774
T_PL = 271
T_PH = 296
I_sat = 200
temp = 13 #Example of a temperature in .csv file
α = 3.75e-5
p_max_T = (P_1 * math.exp(T_AP / T_P1 - T_AP / (temp + 273.15))) / (1 + math.exp(T_APL / (temp + 273.15) - T_APL / T_PL) + math.exp(T_APH / T_PH - T_APH / (temp + 273.15)))
#p_max = (α * I_sat / math.log(1 + α / x)) * (α / (α + x)) * (x / (α + x))**(x / α)
beta_func = lambda x: p_max_T - (α * I_sat / math.log(1 + α / x)) * (α / (α + x)) * (x / (α + x))**(x / α)
beta_test = scipy.optimize.newton(beta_func, 1E-9)
For some reason, optimize.newton finds x=0, which results in a 'division by 0' error.
The initial guess of x is 1E-9. I have tried solving the equation for every temp that is in my .csv file, but none of them should result in x=0.
Any advice or insights would be very welcome.
Thanks!
UPDATE
I've tried applying the bisection method. However, it states that no root is present.
def f(x):
return((P_1 * math.exp(T_AP / T_P1 - T_AP / (temp + 273.15))) / (1 + math.exp(T_APL / (temp + 273.15) - T_APL / T_PL) + math.exp(T_APH / T_PH - T_APH / (temp + 273.15)))-(α * I_sat / math.log(1 + α / temp)) * (α / (α + temp)) * (temp / (α + temp))**(temp / α))
def bisection_method(a, b, tol):
if f(a)*f(b) > 0:
#end function, no root.
print("No root found.")
else:
while (b - a)/2.0 > tol:
midpoint = (a + b)/2.0
if f(midpoint) == 0:
return(midpoint)
elif f(a)*f(midpoint) < 0:
b = midpoint
else:
a = midpoint
return(midpoint)
answer = bisection_method(0, 1, 1E-10)
print("Answer:", answer)