Ask Your Question
0

Error in calling a custom function from sage

asked 5 years ago

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

1 Answer

Sort by » oldest newest most voted
1

answered 5 years ago

rburing gravatar image

updated 5 years ago

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.)

Preview: (hide)
link

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

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

gg gravatar imagegg ( 5 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: 5 years ago

Seen: 20,650 times

Last updated: Feb 20 '20