scipy中univariateSplines无法求差,如何生成自定义节点数组?
Hey there! I totally get how frustrating it can be when you hit a roadblock with SciPy's spline functions—especially when interpolation between UnivariateSplines isn't working as expected. Let's walk through how to generate spline node arrays with your exact desired range and increment, which should help you work through this issue.
First, a quick clarification: when we talk about "spline nodes", we're referring to the x-values where the spline's piecewise segments connect. For SciPy's UnivariateSpline, you can either let the function auto-generate these nodes, or define your own explicitly for full control.
1. Create a Custom Node Array with Your Range & Step Size
To build a node array that matches your desired range and increment, NumPy's linspace and arange functions are your best friends:
Use
np.linspaceif you want a fixed number of evenly spaced nodes across your range:import numpy as np # Define your parameters start = 0 end = 10 total_nodes = 15 # Generate evenly spaced nodes custom_nodes = np.linspace(start, end, total_nodes)Use
np.arangeif you want to specify an exact step size between nodes:import numpy as np start = 0 end = 10 step = 0.5 # Generate nodes with fixed step (add step to end to ensure it's included) custom_nodes = np.arange(start, end + step, step)
2. Use Custom Nodes with UnivariateSpline
Once you have your custom node array, pass it to UnivariateSpline using the t parameter (this sets the interior knots). Just remember: interior knots should be strictly increasing and lie between your data's endpoints (not including them) to avoid errors.
Here's a full example:
from scipy.interpolate import UnivariateSpline import numpy as np # Sample data (replace with your own) x_data = np.linspace(0, 10, 100) y_data = np.sin(x_data) + np.random.normal(0, 0.1, 100) # Generate custom interior nodes (1 to 9, step 1) custom_interior_knots = np.arange(1, 10, 1) # Create spline with custom knots (k=3 for cubic spline, adjust as needed) my_spline = UnivariateSpline(x_data, y_data, t=custom_interior_knots, k=3) # Evaluate the spline at your custom nodes (or any x-values) interpolated_values = my_spline(custom_nodes)
3. Fixing Interpolation Between Splines
If your original issue was calculating differences between two UnivariateSpline objects, using a shared set of custom nodes will align your evaluations perfectly:
# Assume spline_a and spline_b are your two existing UnivariateSplines # Find the overlapping range of both splines min_x = min(spline_a.get_knots()[0], spline_b.get_knots()[0]) max_x = max(spline_a.get_knots()[-1], spline_b.get_knots()[-1]) # Generate common nodes across the overlapping range common_nodes = np.linspace(min_x, max_x, 50) # Evaluate both splines at these nodes vals_a = spline_a(common_nodes) vals_b = spline_b(common_nodes) # Now you can compute the difference easily spline_difference = vals_a - vals_b
内容的提问来源于stack exchange,提问作者Enrico Pascatti

