I'm trying to write a numerical method in python, here is the code in full:
# Newton-Raphson iterative scheme
qin_secs = 100
W = 3
L = 7000
A = W * L
n = 0.04
S = 0.007
b = 100
deltatime = 1
# define the function f(x)
def f(x):
return qin_secs-(((x-b)/deltatime)*A)-((W*x)/n)*((W*x)/((W+2)*x))**0.66*(S)**0.5
# define the derivative of f(x)
def f_prime(x):
return -((A / deltatime) * x) - ((W*(S)**0.5)/n) * (((W*x)/(W + 2*x))**0.66 + (0.66 * x) * (((1/(x)) + (2/W))**0.33) * (W**2)/((W+(2*x))**2))
# define the initial guess
x0 = 101
# define the tolerance
tol = 1e-6
# define the maximum number of iterations
max_iter = 100
# initialize the iteration counter
n = 0
# compute the initial error
error = abs(f(x0))
# iterate until the error is less than the tolerance
# or the maximum number of iterations is reached
while error > tol and n < max_iter:
# update the approximation
x1 = x0 - f(x0) / f_prime(x0)
# update the error
error = abs(f(x1))
# update the iteration counter
n += 1
# update the initial guess
x0 = x1
# print the final approximation
print(x1)
The error appears on the following line:
def f(x):
return qin_secs-(((x-b)/deltatime)*A)-((W*x)/n)*((W*x)/((W+2)*x))**0.66*(S)**0.5
I'm not 100% sure where the error is but I tried the following to bypass the error:
def f(x):
if x == 0:
return 0
return qin_secs-(((x-b)/deltatime)*A)-((W*x)/n)*((W*x)/((W+2)*x))**0.66*(S)**0.5
But no luck, still getting the error. Thanks for the help.