Python – Error adding one to interval

Error adding one to interval… here is a solution to the problem.

Error adding one to interval

Here is 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 it, it works as expected. However, if I change i_min to -52, it doesn’t work and I get:

UnboundLocalError: local variable ‘x’ referenced before assignment

Combing through other answers to this error, I found that most suggest using global variables. But any global variable declarations I’ve tried so far have not worked.
Any help is greatly appreciated.

EDIT: Here is 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

Solution

Simply pass x as an argument to the solver function. This way you don’t depend on global variables.

The code to do this might look like this:

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)

Related Problems and Solutions