0

I am trying to solve an equation for variable 'X' in python where some of the variables in the equation ('ABC, PQR') are output from a function 'calculations'. The problem is, in order to get an output from the function, I need to pass variable X as an argument itself. I am kind of stuck in a loop here. I tried two different approaches but didn't get any success. Is there a way I can solve the equation?

Any help/direction is really appreciated.

My first approach is to start with a small value and run a loop. I tried to use math.isclose() but receive 'math bound error' once the values go off the range and it runs into an infinite loop. The second approach is to write the complete expression and use scipy.optimize fsolve() but I am unable to understand how to properly implement it.

# function
def calculations(X, a, b, c):
    ABC = X*a*b + c
    XYZ = X*b*c + a
    PQR = X*a*c + b

    return ABC, XYZ, PQR

# ABC, PQR is the output from a function which uses X as input
# solve for X
func = 2*ABC + sqrt(PQR*ABC) + X*100*0.5

# Approach 1
X = 0.001
step = 0.001
while True:
    # function call
    Var_ABC, Var_XYZ, Var_PQR = calculations(X, a, b, c)
    func = 2*Var_ABC + math.sqrt(Var_PQR * Var_ABC) + X*100*0.5
    if (math.isclose(func, 0.0, rel_tol=0.1) == True):
        break
    else:
        X = X + step

# Approach 2
# Since I don't know the value of X, how can I get the output from the function and then solve it again?

func_output[0] = calculations(X, a, b, c) # ABC
func_output[2] = calculations(X, a, b, c) # PQR
func = 2* func_output[0] + math.sqrt (func_output[0] * func_output[2] ) + X*100*0.5

from scipy.optimize import fsolve
desired_output_X = fsolve(func, [0.01, 1])
erm0rden
  • 11
  • 3

1 Answers1

0

This may help you getting started with fsolve:

# function of X
def func(X):
    func_output = calculations(X, a, b, c)
    func = 2* func_output[0] + math.sqrt (func_output[0] * func_output[2]) + X*100*0.5
    return func

# extra arguments for calculations function, dummy values used: set them as desired
a,b,c = 1,2,6

# initiating X = 0.01 and solve for X
desired_output_X = fsolve(func, x0 = 0.01)
Mankind_008
  • 2,158
  • 2
  • 9
  • 15