Assume you have a function like
F = lambda x: sin(x)/x
Evaluating F(0.0)
would result in a divide by zero warning, and would not give the expected result of 1.0
. Is it possible to write another function fix_singularity
that would give the desired result when applied to the above function, so that
fix_singularity(F)(0.0) == 1.0
Or formally fix_singularity
should pass the following tests:
import numpy as np
def test_fix_singularity():
F = lambda x: np.sin(x)/x
x = np.array((0.0, pi))
np.testing.assert_array_almost_equal( F(x), [nan, 0] )
np.testing.assert_array_almost_equal( fix_singularity(F)(x), [1, 0] )
One possible implementation is
def fix_singularity(F):
""" Fix the singularity of function F(x) """
def L(x):
f = F(x)
i = np.isnan(f)
f[i] = F(x[i] + 1e-16)
return f
return L
Are there better ways of doing this?
EDIT: Also how can I suppress the warning:
Warning: invalid value encountered in divide