My problem is quite simple. I consider the following Heavside function and I want to interpolate its value for x=0.
Apparently, Python has reached its recursive limit. I am not familiar with Python. Maybe someone can help me to understand my (big?) mistake.
import numpy as np;
from scipy.interpolate import interp1d;
x=np.arange(10)
@np.vectorize
def heaviside(x):
if x<0:
return 0
elif x>0:
return 1
else :
return interp1d(x,heaviside(x))
print(heaviside(0))
CodePudding user response:
If both if conditions x<0
and x>0
fall through, x==0
. Then, the last block of code just calls heaviside(0)
again, leading to direct infinite recursion. The function interp1d
does not even take part in this.
CodePudding user response:
The main problem is that your call on interp1d
which includes a call for heaviside
function also. So interp1d
never gets evaluated because the code will repeatedly try to evaluate heaviside(0)
.
Besides that, you can check for the original documentation here. It indicates that the first two parameters of interp1d
are type of list.
In your code, you provide the heaviside
function with only a number as a parameter. on your call to heaviside(x)
in the last line
I think you can fix this with,
import numpy as np
from scipy.interpolate import interp1d
@np.vectorize
def heaviside(x):
if x < 0:
return 0
elif x > 0:
return 1
else:
return interp1d(x, heaviside(x))
precision = 1e-4
your_input = np.arange(-1, 1, precision)
print(heaviside(your_input).shape)
print(heaviside(your_input))
# output here
>>> (20000,)
>>> [0 0 0 ... 1 1 1]
You can observe the output via indexing but I doubt you'll ever get anything other than 0 & 1 (a cause of linear interpolation.)
Plus here is documentation for @np.vectorize
.