Skip to content

Instantly share code, notes, and snippets.

@bamford
Created June 25, 2018 11:53
Show Gist options
  • Save bamford/1f3010e8ed4c6001136c53d52c3b9a9d to your computer and use it in GitHub Desktop.
Save bamford/1f3010e8ed4c6001136c53d52c3b9a9d to your computer and use it in GitHub Desktop.
How to obtain all the values for the n-th root of a number using sympy
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {},
"cell_type": "markdown",
"source": "How to obtain all the values for the $n$-th root of a number using sympy"
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "from sympy import symbols, solve",
"execution_count": 1,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "x, y, n = symbols('x, y, n')",
"execution_count": 2,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "z = x**n - y",
"execution_count": 3,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "roots = solve(z.subs({n: 5, y: 2}))\nroots",
"execution_count": 4,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 4,
"data": {
"text/plain": "[2**(1/5),\n -2**(1/5)/4 + 2**(1/5)*sqrt(5)/4 - 2**(1/5)*I*sqrt(sqrt(5)/8 + 5/8),\n -2**(1/5)/4 + 2**(1/5)*sqrt(5)/4 + 2**(1/5)*I*sqrt(sqrt(5)/8 + 5/8),\n -2**(1/5)*sqrt(5)/4 - 2**(1/5)/4 - 2**(1/5)*I*sqrt(-sqrt(5)/8 + 5/8),\n -2**(1/5)*sqrt(5)/4 - 2**(1/5)/4 + 2**(1/5)*I*sqrt(-sqrt(5)/8 + 5/8)]"
},
"metadata": {}
}
]
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "froots = [r.evalf() for r in roots]\nfroots",
"execution_count": 5,
"outputs": [
{
"output_type": "execute_result",
"execution_count": 5,
"data": {
"text/plain": "[1.14869835499704,\n 0.35496731310463 - 1.09247705577745*I,\n 0.35496731310463 + 1.09247705577745*I,\n -0.929316490603148 - 0.675187952399881*I,\n -0.929316490603148 + 0.675187952399881*I]"
},
"metadata": {}
}
]
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"hide_input": false,
"latex_envs": {
"eqNumInitial": 1,
"eqLabelWithNumbers": true,
"current_citInitial": 1,
"cite_by": "apalike",
"bibliofile": "biblio.bib",
"LaTeX_envs_menu_present": true,
"labels_anchors": false,
"latex_user_defs": false,
"user_envs_cfg": false,
"report_style_numbering": false,
"autocomplete": true,
"hotkeys": {
"equation": "Ctrl-E",
"itemize": "Ctrl-I"
}
},
"language_info": {
"name": "python",
"version": "3.6.4",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
},
"gist": {
"id": "",
"data": {
"description": "How to obtain all the values for the n-th root of a number using sympy",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment