{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#A helpful script for Exercise 3.4.8.\n",
    "\n",
    "#Here is the data for Exercise 3.4.8, in time/population pairs:\n",
    "data = [[0, 9.6], [1, 18.3], [2, 29], [3, 47.2], [4, 71.1], [5, 119.1], [6, 174.6], [7, 257.3], [8, 350.7], [9, 441], [10, 513.3], [11, 559.7], [12, 594.8], [13, 629.4], [14, 640.8], [15, 651.1], [16, 655.9], [17, 659.6]]\n",
    "N = len(data);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#A plot:\n",
    "plt1 = scatter_plot(data);\n",
    "show(plt1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Given that u(0) = 9.6, the solution to the logistic equation with intrinsic growth rate \"r\" and carrying capacity \"K\" is\n",
    "var('t K r');\n",
    "u(t,K,r) = K/(1+exp(-r*t)*(K/9.6-1)); #The model function to fit\n",
    "SS = function('SS')(K,r);\n",
    "SS(K,r) = add((u(data[i][0],K,r)-data[i][1])^2 for i in range(N));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Now minimize SS(K,r) with respect to K and r."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "SageMath 9.2",
   "language": "sage",
   "name": "sagemath"
  },
  "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.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}