help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
scipy-scientific
/
notebooks
RSK World
scipy-scientific
Scientific Computing with SciPy
notebooks
  • 01_optimization.ipynb19.5 KB
  • 02_integration.ipynb7.4 KB
  • 03_interpolation.ipynb8.8 KB
  • 04_statistics.ipynb8.8 KB
  • 05_signal_processing.ipynb16.6 KB
03_interpolation.ipynb
notebooks/03_interpolation.ipynb
Raw Download
Find: Go to:
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# SciPy Interpolation and Fitting\n",
    "\n",
    "<!--\n",
    "Author: RSK World\n",
    "Website: https://rskworld.in\n",
    "Email: help@rskworld.in\n",
    "Phone: +91 93305 39277\n",
    "-->\n",
    "\n",
    "This notebook demonstrates interpolation and curve fitting with SciPy.\n",
    "\n",
    "## Topics Covered:\n",
    "1. 1D Interpolation\n",
    "2. 2D Interpolation\n",
    "3. Curve Fitting\n",
    "4. Spline Interpolation\n",
    "5. RBF Interpolation\n",
    "6. Extrapolation\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Author: RSK World - https://rskworld.in\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy.interpolate import interp1d, griddata, UnivariateSpline, RBFInterpolator\n",
    "from scipy.optimize import curve_fit\n",
    "\n",
    "print(\"SciPy Interpolation and Fitting Examples\")\n",
    "print(\"Author: RSK World - https://rskworld.in\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. 1D Interpolation\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate sample data\n",
    "np.random.seed(42)\n",
    "x_known = np.linspace(0, 10, 10)\n",
    "y_known = np.sin(x_known) + 0.1 * np.random.randn(len(x_known))\n",
    "\n",
    "# Create interpolation functions\n",
    "linear = interp1d(x_known, y_known, kind='linear')\n",
    "cubic = interp1d(x_known, y_known, kind='cubic')\n",
    "spline = UnivariateSpline(x_known, y_known, s=0)\n",
    "\n",
    "# Evaluate at new points\n",
    "x_new = np.linspace(0, 10, 100)\n",
    "y_linear = linear(x_new)\n",
    "y_cubic = cubic(x_new)\n",
    "y_spline = spline(x_new)\n",
    "y_true = np.sin(x_new)\n",
    "\n",
    "print(f\"Interpolation methods: linear, cubic, spline\")\n",
    "print(f\"Original points: {len(x_known)}\")\n",
    "print(f\"Interpolated points: {len(x_new)}\")\n",
    "\n",
    "# Visualize\n",
    "plt.figure(figsize=(12, 6))\n",
    "plt.scatter(x_known, y_known, color='red', s=100, zorder=5, label='Known data points')\n",
    "plt.plot(x_new, y_true, 'k--', linewidth=2, alpha=0.5, label='True function: sin(x)')\n",
    "plt.plot(x_new, y_linear, 'b-', linewidth=1.5, label='Linear interpolation')\n",
    "plt.plot(x_new, y_cubic, 'g-', linewidth=1.5, label='Cubic interpolation')\n",
    "plt.plot(x_new, y_spline, 'm-', linewidth=1.5, label='Spline interpolation')\n",
    "plt.xlabel('x', fontsize=12)\n",
    "plt.ylabel('y', fontsize=12)\n",
    "plt.title('1D Interpolation Methods', fontsize=14, fontweight='bold')\n",
    "plt.legend()\n",
    "plt.grid(True, alpha=0.3)\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 2D Interpolation\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate sample 2D data\n",
    "np.random.seed(42)\n",
    "x_known = np.random.rand(20) * 10\n",
    "y_known = np.random.rand(20) * 10\n",
    "z_known = np.sin(x_known) * np.cos(y_known) + 0.1 * np.random.randn(len(x_known))\n",
    "\n",
    "# Create regular grid for interpolation\n",
    "x_grid = np.linspace(0, 10, 50)\n",
    "y_grid = np.linspace(0, 10, 50)\n",
    "X_grid, Y_grid = np.meshgrid(x_grid, y_grid)\n",
    "\n",
    "# Interpolate using different methods\n",
    "z_linear = griddata((x_known, y_known), z_known, (X_grid, Y_grid), method='linear')\n",
    "z_cubic = griddata((x_known, y_known), z_known, (X_grid, Y_grid), method='cubic')\n",
    "\n",
    "print(f\"2D Interpolation methods: linear, cubic\")\n",
    "print(f\"Known points: {len(x_known)}\")\n",
    "print(f\"Grid size: {len(x_grid)} × {len(y_grid)}\")\n",
    "\n",
    "# Visualize\n",
    "fig, axes = plt.subplots(1, 3, figsize=(15, 5))\n",
    "\n",
    "# Original data\n",
    "axes[0].scatter(x_known, y_known, c=z_known, s=100, cmap='viridis', edgecolors='black')\n",
    "plt.colorbar(axes[0].collections[0], ax=axes[0], label='z')\n",
    "axes[0].set_xlabel('x', fontsize=12)\n",
    "axes[0].set_ylabel('y', fontsize=12)\n",
    "axes[0].set_title('Original Data Points', fontsize=12, fontweight='bold')\n",
    "axes[0].grid(True, alpha=0.3)\n",
    "\n",
    "# Linear interpolation\n",
    "contour1 = axes[1].contourf(X_grid, Y_grid, z_linear, levels=20, cmap='viridis')\n",
    "plt.colorbar(contour1, ax=axes[1], label='z')\n",
    "axes[1].set_xlabel('x', fontsize=12)\n",
    "axes[1].set_ylabel('y', fontsize=12)\n",
    "axes[1].set_title('Linear Interpolation', fontsize=12, fontweight='bold')\n",
    "axes[1].grid(True, alpha=0.3)\n",
    "\n",
    "# Cubic interpolation\n",
    "contour2 = axes[2].contourf(X_grid, Y_grid, z_cubic, levels=20, cmap='viridis')\n",
    "plt.colorbar(contour2, ax=axes[2], label='z')\n",
    "axes[2].set_xlabel('x', fontsize=12)\n",
    "axes[2].set_ylabel('y', fontsize=12)\n",
    "axes[2].set_title('Cubic Interpolation', fontsize=12, fontweight='bold')\n",
    "axes[2].grid(True, alpha=0.3)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate noisy data\n",
    "np.random.seed(42)\n",
    "x_data = np.linspace(0, 10, 30)\n",
    "y_true = 2 * np.exp(-0.5 * x_data) * np.sin(2 * x_data)\n",
    "y_data = y_true + 0.2 * np.random.randn(len(x_data))\n",
    "\n",
    "# Define model function\n",
    "def exponential_decay(x, a, b, c, d):\n",
    "    return a * np.exp(-b * x) * np.sin(c * x + d)\n",
    "\n",
    "# Fit exponential model\n",
    "popt, pcov = curve_fit(exponential_decay, x_data, y_data, p0=[2, 0.5, 2, 0])\n",
    "\n",
    "print(f\"Exponential model parameters:\")\n",
    "print(f\"  a = {popt[0]:.4f}, b = {popt[1]:.4f}\")\n",
    "print(f\"  c = {popt[2]:.4f}, d = {popt[3]:.4f}\")\n",
    "\n",
    "# Calculate R²\n",
    "ss_res = np.sum((y_data - exponential_decay(x_data, *popt))**2)\n",
    "ss_tot = np.sum((y_data - np.mean(y_data))**2)\n",
    "r2 = 1 - (ss_res / ss_tot)\n",
    "\n",
    "print(f\"R²: {r2:.4f}\")\n",
    "\n",
    "# Generate fitted curve\n",
    "x_fit = np.linspace(0, 10, 200)\n",
    "y_fit = exponential_decay(x_fit, *popt)\n",
    "\n",
    "# Visualize\n",
    "plt.figure(figsize=(12, 6))\n",
    "plt.scatter(x_data, y_data, alpha=0.7, color='blue', s=50, label='Noisy data')\n",
    "plt.plot(x_data, y_true, 'k--', linewidth=2, alpha=0.7, label='True function')\n",
    "plt.plot(x_fit, y_fit, 'r-', linewidth=2, label=f'Exponential fit (R²={r2:.3f})')\n",
    "plt.xlabel('x', fontsize=12)\n",
    "plt.ylabel('y', fontsize=12)\n",
    "plt.title('Curve Fitting', fontsize=14, fontweight='bold')\n",
    "plt.legend()\n",
    "plt.grid(True, alpha=0.3)\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Spline Interpolation\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate noisy data\n",
    "np.random.seed(42)\n",
    "x_known = np.linspace(0, 10, 15)\n",
    "y_known = np.sin(x_known) + 0.2 * np.random.randn(len(x_known))\n",
    "\n",
    "# Create splines with different smoothing factors\n",
    "spline_smooth = UnivariateSpline(x_known, y_known, s=len(x_known))\n",
    "spline_interp = UnivariateSpline(x_known, y_known, s=0)\n",
    "\n",
    "# Evaluate\n",
    "x_new = np.linspace(0, 10, 200)\n",
    "y_smooth = spline_smooth(x_new)\n",
    "y_interp = spline_interp(x_new)\n",
    "y_true = np.sin(x_new)\n",
    "\n",
    "print(f\"Smoothing spline (s={len(x_known)}): smoother, less accurate\")\n",
    "print(f\"Interpolating spline (s=0): passes through all points\")\n",
    "\n",
    "# Visualize\n",
    "plt.figure(figsize=(12, 6))\n",
    "plt.scatter(x_known, y_known, color='red', s=100, zorder=5, label='Known data points')\n",
    "plt.plot(x_new, y_true, 'k--', linewidth=2, alpha=0.5, label='True function: sin(x)')\n",
    "plt.plot(x_new, y_smooth, 'b-', linewidth=2, label='Smoothing spline')\n",
    "plt.plot(x_new, y_interp, 'g-', linewidth=2, label='Interpolating spline')\n",
    "plt.xlabel('x', fontsize=12)\n",
    "plt.ylabel('y', fontsize=12)\n",
    "plt.title('Spline Interpolation: Smoothing vs Interpolation', fontsize=14, fontweight='bold')\n",
    "plt.legend()\n",
    "plt.grid(True, alpha=0.3)\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
264 lines•8.8 KB
json
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer