Files
jupyter-collection/scientific-computing-2/auto_examples_jupyter_3/plot_curve_fit.ipynb
2025-10-21 11:20:44 +08:00

86 lines
2.3 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Curve fitting\n\nDemos a simple curve fitting\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First generate some data\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import numpy as np\n\n# Seed the random number generator for reproducibility\nrng = np.random.default_rng(27446968)\n\nx_data = np.linspace(-5, 5, num=50)\nnoise = 0.01 * np.cos(100 * x_data)\na, b = 2.9, 1.5\ny_data = a * np.cos(b * x_data) + noise\n\n# And plot it\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(6, 4))\nplt.scatter(x_data, y_data)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now fit a simple sine function to the data\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import scipy as sp\n\n\ndef test_func(x, a, b, c):\n return a * np.sin(b * x + c)\n\n\nparams, params_covariance = sp.optimize.curve_fit(\n test_func, x_data, y_data, p0=[2, 1, 3]\n)\n\nprint(params)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And plot the resulting curve on the data\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"plt.figure(figsize=(6, 4))\nplt.scatter(x_data, y_data, label=\"Data\")\nplt.plot(x_data, test_func(x_data, *params), label=\"Fitted function\")\n\nplt.legend(loc=\"best\")\n\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.11"
}
},
"nbformat": 4,
"nbformat_minor": 0
}