Ask Your Question
0

ValueError: cannot convert n to int

asked 8 years ago

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?

Preview: (hide)

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 ( 8 years ago )

2 Answers

Sort by » oldest newest most voted
1

answered 8 years ago

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
Preview: (hide)
link

Comments

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

kcrisman gravatar imagekcrisman ( 8 years ago )
1

answered 8 years ago

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)
Preview: (hide)
link

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 ( 8 years ago )

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 ( 8 years ago )

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: 8 years ago

Seen: 974 times

Last updated: Apr 11 '17