Skip to content

Instantly share code, notes, and snippets.

@cegme
Last active March 25, 2025 19:43
Show Gist options
  • Select an option

  • Save cegme/7b8a691bc5d46e49499fa5a42165643b to your computer and use it in GitHub Desktop.

Select an option

Save cegme/7b8a691bc5d46e49499fa5a42165643b to your computer and use it in GitHub Desktop.
Interpolation for fitting curves. Takes 2 or more points and returns the interpolated coordinates.
import numpy as np
from scipy.optimize import curve_fit
def exponential_interpolation(points, N=330):
"""
Interpolates an exponential curve from 2 to 5 ordered points and returns N interpolated points.
Parameters:
- points: List of tuples [(x1, y1), (x2, y2), ...] (2 or more points)
- N: Number of interpolated points to return (330)
Returns:
- interpolated_x: Array of N x-values
- interpolated_y: Array of corresponding y-values
"""
if not (2 <= len(points)):
raise ValueError("Function requires at least 2 points.")
# Extract x and y values
x_data, y_data = zip(*points)
x_data = np.array(x_data, dtype=np.float64)
y_data = np.array(y_data, dtype=np.float64)
# Normalize x-values for numerical stability
x_min = np.min(x_data)
x_scaled = x_data - x_min # Shift x to start from 0
# Define the exponential function
def exp_func(x, a, b):
return a * np.exp(b * x)
# Initial guesses for parameters
a_init = y_data[0] # Start with first y-value
b_init = np.log(y_data[-1] / y_data[0]) / (x_data[-1] - x_data[0]) # Estimate b
# Fit curve using nonlinear regression
params, _ = curve_fit(exp_func, x_scaled, y_data, p0=[a_init, b_init], maxfev=5000)
a_opt, b_opt = params
# Generate interpolated x values
x_interp = np.linspace(min(x_data), max(x_data), N)
x_interp_scaled = x_interp - x_min # Apply the same shift
# Compute interpolated y values
y_interp = exp_func(x_interp_scaled, a_opt, b_opt)
return x_interp, y_interp
def main():
# Example Usage:
rinitial = 54
rfinal = 168
# points = [(0, rinitial), (329, rfinal)]
# points = [(1, 5), (2, 15), (3, 40), (4, 90)]
points = [(0, rfinal), (329, rinitial)]
N = 330 # Number of interpolated points
x_interp, y_interp = exponential_interpolation(points, N)
# Plot results
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 5))
plt.scatter(*zip(*points), color='red', label="Given Points", zorder=3)
plt.plot(x_interp, y_interp, color='blue', label="Interpolated Exponential Curve")
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Fixed Exponential Interpolation')
plt.legend()
plt.grid(True)
plt.show()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment