{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Solving non-linear equations\n", "\n", "^ca27a3\n", "\n", "## Introduction\n", "\n", "## Prerequisites\n", "\n", "``` python\n", "import numpy\n", "import scipy\n", "import sympy\n", "```\n", "\n", "## fsolve from SciPy\n", "\n", "``` python\n", "from scipy.optimize import fsolve\n", "\n", "def equations(vars):\n", " x, y = vars\n", " eq1 = x**2 + y**2 - 25\n", " eq2 = x**2 - y\n", " return [eq1, eq2]\n", "\n", "initial_guess = [1, 1]\n", "solution = fsolve(equations, initial_guess)\n", "print(\"Solution:\", solution)\n", "```\n", "\n", "## root from SciPy\n", "\n", "``` python\n", "from scipy.optimize import root\n", "\n", "def equations(vars):\n", " x, y = vars\n", " eq1 = x**2 + y**2 - 25\n", " eq2 = x**2 - y\n", " return [eq1, eq2]\n", "\n", "initial_guess = [1, 1]\n", "solution = root(equations, initial_guess)\n", "print(\"Solution:\", solution.x)\n", "```\n", "\n", "## minimize from SciPy\n", "\n", "``` python\n", "from scipy.optimize import minimize\n", "\n", "# Define the equations\n", "def equation1(x, y):\n", " return x**2 + y**2 - 25\n", "\n", "def equation2(x, y):\n", " return x**2 - y\n", "\n", "# Define the objective function for optimization\n", "def objective(xy):\n", " x, y = xy\n", " return equation1(x, y)**2 + equation2(x, y)**2\n", "\n", "# Initial guess\n", "initial_guess = [1, 1]\n", "\n", "# Perform optimization\n", "result = minimize(objective, initial_guess)\n", "solution_optimization = result.x\n", "\n", "print(\"Optimization Method Solution:\", solution_optimization)\n", "```\n", "\n", "## nsolve from SymPy\n", "\n", "``` python\n", "from sympy import symbols, Eq, nsolve\n", "\n", "# Define the variables\n", "x, y = symbols('x y')\n", "\n", "# Define the equations\n", "eq1 = Eq(x**2 + y**2, 25)\n", "eq2 = Eq(x - y, 0)\n", "\n", "# Initial guess for the solution\n", "initial_guess = [1, 1]\n", "\n", "# Use nsolve to find the solution\n", "solution = nsolve([eq1, eq2], [x, y], initial_guess)\n", "print(\"Solution:\", solution)\n", "```\n", "\n", "## newton_method from NumPy\n", "\n", "``` python\n", "import numpy as np\n", "\n", "def equations(vars):\n", " x, y = vars\n", " eq1 = x**2 + y**2 - 25\n", " eq2 = x**2 - y\n", " return np.array([eq1, eq2])\n", "\n", "def newton_method(initial_guess, tolerance=1e-6, max_iter=100):\n", " vars = np.array(initial_guess, dtype=float)\n", " for _ in range(max_iter):\n", " J = np.array([[2 * vars[0], 2 * vars[1]], [2 * vars[0], -1]])\n", " F = equations(vars)\n", " delta = np.linalg.solve(J, -F)\n", " vars += delta\n", " if np.linalg.norm(delta) < tolerance:\n", " return vars\n", "\n", "initial_guess = [1, 1]\n", "solution = newton_method(initial_guess)\n", "print(\"Solution:\", solution)\n", "```" ], "id": "2ba3c111-8a56-4d09-b043-cdd8c5528e00" } ], "nbformat": 4, "nbformat_minor": 5, "metadata": {} }