我在处理python代码中的异常时遇到问题。当尝试使用“线性”方法在特定网格上进行三维插值时,会出现错误;这会产生一个QhullError。 使用“最近的”插值效果良好。 因此,我想使用“try/except”捕捉“QhullError”
当我运行代码时,我得到
NameError: name 'QhullError' is not defined
我还尝试了一个自定义类来处理异常,但这根本无法捕获任何内容
你知道我错过了什么吗
非常感谢
找到下面的代码:
import numpy as np
import warnings
from scipy.interpolate import LinearNDInterpolator as Lin3DInterp
from scipy.interpolate import NearestNDInterpolator as Near3DInterp
from random import random
# %% Here I tried a custom class to handle my exception... didn't work either
# class QhullError(Exception):
# pass
# %%
# choosing interpolation method : 'linear' or 'nearest'
InterpMethod = 'linear'
# evenly spaced grid
grid_points = np.squeeze(np.array([[np.linspace(0, 9, 10)],
[np.linspace(0, 9, 10)],
[np.linspace(0, 9, 10)]]).transpose())
# some random values
grid_points_values = random()*grid_points
if InterpMethod == 'nearest':
# this works fine
interp_func = Near3DInterp(grid_points, grid_points_values)
elif InterpMethod == 'linear':
try:
# QhullError here, trying to catch that
interp_func = Lin3DInterp(grid_points, grid_points_values)
except QhullError:
warnings.warn('QhullError : linear interpolation failed, '
'using ''nearest'' method instead')
interp_func = Near3DInterp(grid_points, grid_points_values)
您应该能够从此处导入它:
相关问题 更多 >
编程相关推荐