Skip to content

Instantly share code, notes, and snippets.

@cbcunc
Last active August 29, 2015 14:10
Show Gist options
  • Save cbcunc/598ffb120cbeb0991225 to your computer and use it in GitHub Desktop.
Save cbcunc/598ffb120cbeb0991225 to your computer and use it in GitHub Desktop.
Converge on root of function for a given accuracy and initial guess.
Display the source blob
Display the rendered blob
Raw
{
"metadata": {
"name": "",
"signature": "sha256:3de1014f6d7d8fc91796d1d2ebef97f0f4c357bc4d9ef643209a449f972b9242"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "code",
"collapsed": false,
"input": [
"from math import cos, sin\n",
"def f(x):\n",
" \"\"\"To find the root of x = cos(x),\n",
" the function is cos(x) - x.\"\"\"\n",
" return cos(x) - x"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 35
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def f_prime(x):\n",
" \"\"\"The derivative of f(x) = cos(x) - x\"\"\"\n",
" return -sin(x) - 1"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 36
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"def guess(f, f_prime, x0):\n",
" \"\"\"A generator function to yield\n",
" succesive guesses for Newton's Method.\"\"\"\n",
" x = x0\n",
" while True:\n",
" yield x\n",
" x = x - (f(x)/f_prime(x))"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 37
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Converge on the answer.\n",
"x0 = 0\n",
"iterations = 0\n",
"places = 6\n",
"accuracy = 10 ** (-places)\n",
"for x in guess(f, f_prime, x0):\n",
" if abs(f(x)) < accuracy:\n",
" break\n",
" iterations += 1"
],
"language": "python",
"metadata": {},
"outputs": [],
"prompt_number": 38
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"print \"The root of x = cos(x) is %.*f radians.\" % (places + 1, x)\n",
"print \"Calculated to within %f accuracy in %u iteration(s).\" % (accuracy, iterations)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"output_type": "stream",
"stream": "stdout",
"text": [
"The root of x = cos(x) is 0.7390851 radians.\n",
"Calculated to within 0.000001 accuracy in 4 iteration(s).\n"
]
}
],
"prompt_number": 39
}
],
"metadata": {}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment