Ask Your Question
0

Error in calling a custom function from sage

asked 2020-02-20 15:21:09 +0100

gg gravatar image

I used this guide to add module containing some utility to the sage.

My module (myfunc.py) looks like this:

def perm(n, r):
    return factorial(n)/factorial(n-r)

def comb(n, r):
    return perm(n, r)/factorial(r)

To import the module I use the following import statement:

sage: from myfunc import perm

So far so good.

When I call the perm() or comb() function. I get the following error:

 1 def perm(n, r):
 ----> 2     return factorial(n)/factorial(n-r)
 3 
 4 def comb(n, r):
 5     return perm(n, r)/factorial(r)

NameError: name 'factorial' is not defined
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2020-02-20 16:16:36 +0100

rburing gravatar image

updated 2020-02-20 16:16:57 +0100

When you create a Python module and you want to use external code (such as factorial), you have to import it explicitly (another difference is that you do not have the luxury of SageMath's preparser, as mentioned in the linked post). This is for namespace reasons; if it didn't work this way then variables could easily get mixed up across modules, and life would be hell.

So you have to find out where factorial lives. In a SageMath session, entering factorial? will also show you the file it's located in, which is (...)/site-packages/sage/functions/other.py. Since site-packages is always in sys.path, we can import factorial as follows:

from sage.functions.other import factorial

Adding this line to the top of your module will fix your problem.

(By the way, there is already a binomial function.)

edit flag offensive delete link more

Comments

Thanks for the reply, my module is working now. I discovered the binomial() function after posting the question. Is there binomcdf() or something similar available too?

gg gravatar imagegg ( 2020-02-20 16:28:39 +0100 )edit

@rburing Okay, I found most of the statistical related functions in scipy.

gg gravatar imagegg ( 2020-02-21 18:18:06 +0100 )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: 2020-02-20 15:21:09 +0100

Seen: 20,342 times

Last updated: Feb 20 '20