On 19/03/2020 20:18, David Collett wrote:
Hi, everyone. I'm new to python and to sympy.
On the sympy documentation site
(https://docs.sympy.org/latest/tutorial/simplification.html#example-continued-fractions),
near the end is the following script:
def list_to_frac(l): expr = Integer(0) for i in reversed(l[1:]): expr
+= i expr = 1/expr return l[0] + expr
print(list_to_frac([x, y, z]))
__________
The output they show (in the SymPy Live Shell) is:
x + (1 / (y + 1/z))
However, when I copied this to a text file and run it from the
terminal (MacOS, Python 3.x), I get the following error:
NameError: name 'x' is not defined
How do I solve this problem?
Notice that as it is your script makes no reference to SymPy, even
though you have presumably installed it.
Your script needs to start by importing SymPy and creating the desired
algebraic symbols, e.g.
import sympy
from sympy import symbols
x,y,z=symbols("x y z")
This makes x reference the SymPy symbol "x", and likewise for y, and z
Note there are various other ways to achieve this, such as:
from sympy.abc import x,y,z
(If instead of x, y, z, I substitute numbers, such
aslist_to_frac([1,1,3,1,1,5,1,1,7])then a fraction is returned
(1463/822)in this case.
I am not clear if the fraction was what you wanted, or if you desired
the continued fraction expression itself. I experimented a bit using
UnevaluatedExpr, but it isn't easy to get a clean looking continued
fraction expression when using integers. However you could use a list
such as [x1,x1,x3,x1,x1,x5,x1,x1,x7] thus:
x1,x3,x5,x7=symbols("x1 x3 x5 x7")
list_to_frac( [x1,x1,x3,x1,x1,x5,x1,x1,x7])
producing the result:
x1 + 1/(x1 + 1/(x3 + 1/(x1 + 1/(x1 + 1/(x5 + 1/(x1 + 1/(x1 + 1/x7)))))))
If however, you just wanted the answer converted to a floating point
number, then try
N(list_to_frac([1,1,3,1,1,5,1,1,7]))
David
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/sympy/7ef39382-a7ef-1527-24b5-f3e7871d0908%40dbailey.co.uk.