|
6 | 6 | "metadata": {},
|
7 | 7 | "source": [
|
8 | 8 | "# Python everything, exercise:\n",
|
9 |
| - "## Nth root algorithm for computing $\\sqrt[n] x$\n", |
10 |
| - "**Nth root algorithm** computes the *nth root* of a given positive number $x$ by\n", |
| 9 | + "## Nth root algorithm for computing $\\sqrt[n] a$\n", |
| 10 | + "**Nth root algorithm** computes the *nth root* of a given positive number $a$ by\n", |
11 | 11 | " 1) $x_0 \\leftarrow$ some initial guess <br>\n",
|
12 | 12 | " 2) for $k=0,1,2...$ do: <br>\n",
|
13 |
| - "$\\;\\;\\;\\; x_{k+1}=\\frac{1}{n}((n-1)x_k+\\frac{x}{x^{n-1}_k})$\n", |
| 13 | + "$\\;\\;\\;\\;\\Large x_{k+1}=\\frac{1}{n}((n-1)x_k+\\frac{a}{x^{n-1}_k})$\n", |
14 | 14 | "\n",
|
15 | 15 | "YouTube Channel: **@ostad-ai**\n",
|
16 | 16 | "<br>The Python code is at: https://github.com/ostad-ai/Python-Everything"
|
|
19 | 19 | {
|
20 | 20 | "cell_type": "code",
|
21 | 21 | "execution_count": 1,
|
| 22 | + "id": "80c175d2", |
| 23 | + "metadata": {}, |
| 24 | + "outputs": [], |
| 25 | + "source": [ |
| 26 | + "def nth_root(a,n=2,x0=1,iter=20):\n", |
| 27 | + " xk=x0\n", |
| 28 | + " n1=n-1\n", |
| 29 | + " for _ in range(iter):\n", |
| 30 | + " xk=(n1*xk+a/xk**n1)/n\n", |
| 31 | + " return xk" |
| 32 | + ] |
| 33 | + }, |
| 34 | + { |
| 35 | + "cell_type": "code", |
| 36 | + "execution_count": 2, |
22 | 37 | "id": "d757f8ac",
|
23 | 38 | "metadata": {},
|
24 | 39 | "outputs": [
|
|
31 | 46 | }
|
32 | 47 | ],
|
33 | 48 | "source": [
|
34 |
| - "def nth_root(x,n=2,x0=1,iter=20):\n", |
35 |
| - " xk=x0\n", |
36 |
| - " n1=n-1\n", |
37 |
| - " for _ in range(iter):\n", |
38 |
| - " xk=(n1*xk+x/xk**n1)/n\n", |
39 |
| - " return xk\n", |
40 |
| - "x=2\n", |
| 49 | + "a=2\n", |
41 | 50 | "n=3\n",
|
42 |
| - "print(f'{n}th root of {x} is:{nth_root(x,n)}')" |
| 51 | + "print(f'{n}th root of {a} is:{nth_root(a,n)}')" |
43 | 52 | ]
|
44 | 53 | },
|
45 | 54 | {
|
|
0 commit comments