So here's my code:
from sympy.solvers import nsolve
from sympy import Symbol
def solver(I):
return nsolve(x-3*(1-2.73**-x), I, verify=False)
i_min=-51
i_max=100
z=0
x = Symbol('x')
for i in range(i_min,i_max):
y=z
z=solver(i)
if y!=z: continue
print(z)
When I run this it works as expected. If I change i_min to -52 though, it doesn't work and I get:
UnboundLocalError: local variable 'x' referenced before assignment
Combing through other answers about this error, I saw that most suggest using global variables. But so far any global variable declaration I've tried hasn't worked. Any help is greatly appreciated.
EDIT: Here's the entire log:
UnboundLocalError Traceback (most recent call
last)
<ipython-input-3-1dfdd15c7bf8> in <module>()
11 for i in range(i_min,i_max):
12 y=z
---> 13 z=solver(i,x)
14 if y!=z: continue
15 print(z)
<ipython-input-3-1dfdd15c7bf8> in solver(I, x)
3
4 def solver(I,x='x'):
----> 5 return nsolve(x-3*(1-2.73**-x), I, verify=False)
6
7 i_min=-55
/home/... in nsolve(*args, **kwargs)
2752
2753 f = lambdify(fargs, f, modules)
-> 2754 return findroot(f, x0, **kwargs)
2755
2756 if len(fargs) > f.cols:
/home... in findroot(ctx, f, x0, solver, tol, verbose, verify,
**kwargs)
965 if error < tol * max(1, norm(x)) or i >= maxsteps:
966 break
--> 967 if not isinstance(x, (list, tuple, ctx.matrix)):
968 xl = [x]
969 else:
UnboundLocalError: local variable 'x' referenced before assignment
Simply pass x into the solver function as a parameter. This way you are not relying on global variables.
The code for doing this may look something like:
from sympy.solvers import nsolve
from sympy import Symbol
def solver(I, x):
return nsolve(x-3*(1-2.73**-x), I, verify=False)
i_min=-51
i_max=100
z=0
x = Symbol('x')
for i in range(i_min,i_max):
y=z
z=solver(i, x)
if y!=z: continue
print(z)
From what your code looks now
you could easily rewrite it to:
def solver(I, x='x'):
return nsolve(x-3*(1-2.73**-x), I, verify=False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With