Ask Your Question
0

ValueError: cannot convert n to int

asked 2017-04-10 18:34:12 -0500

Ruzil gravatar image

I want to do the following

var('n')

prod([k for k in range(1,n)])

But I get the following error: ValueError: cannot convert n to int

Is there some way to do this that does not involve writing a for loop?

edit retag flag offensive close merge delete

Comments

Are you trying to do a symbolic product? If n does not have a specific value then you won't get factorial(n-1) which I suppose is what you want.

kcrisman gravatar imagekcrisman ( 2017-04-10 19:55:13 -0500 )edit

2 answers

Sort by ยป oldest newest most voted
1

answered 2017-04-11 14:34:43 -0500

mforets gravatar image

SymPy's product function does transform that particular symbolic product into the factorial:

sage: from sympy import product, symbols
sage: i, n = symbols('i, n')
sage: product(i, (i, 1, n-1))
factorial(n - 1)

It makes me think that for prod it is a feature which hasn't been implemented but perhaps i'm mistaken. Note that sum has a nicer behavior: for instance sum(1/i, i, 1, n) returns harmonic_number(n).

One alternative is not using prod but just factorial(n-1), as already suggested by kcrisman. Another alternative is to define a Python's lambda function (more on this here), as in:

sage: someProduct = lambda n : prod([i for i in range(1, n)])
sage: someProduct(10)
362880
edit flag offensive delete link more

Comments

The lambda might be what this user needs, that is a good idea.

kcrisman gravatar imagekcrisman ( 2017-04-11 21:20:04 -0500 )edit
1

answered 2017-04-11 16:53:25 -0500

nbruin gravatar image

The symbolic product exists somewhere already (probably in Maxima?), so with some trickery you can get something that looks like it:

sage: function("f")
f
sage: var("n")
n
sage: function("f")
f
sage: P=exp(sum(log(f(x)),x,1,n-1)); P
product(f(x), x, 1, n - 1)

At this point, P.operator is just a formal object: sage itself doesn't know anything about it:

sage: product=P.operator()
sage: product(x,x,1,n).simplify_full()
product(x, x, 1, n)

whereas

sage: exp(sum(log(x),x,1,n))
factorial(n)
edit flag offensive delete link more

Comments

interesting. it would be nice to have these symbolic products though, similarly to the symbolic sum. an application would be to represent / compute infinite products..

mforets gravatar imagemforets ( 2017-04-12 03:32:45 -0500 )edit

It's just a matter of hooking them in! As the answers show, sympy and maxima already have them. Maxima can't do much with them, though.

nbruin gravatar imagenbruin ( 2017-04-12 17:05:18 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2017-04-10 18:34:12 -0500

Seen: 333 times

Last updated: Apr 11