Ask Your Question
0

Error in calling a custom function from sage

asked 2020-02-20 08:21:09 -0500

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 09:16:36 -0500

rburing gravatar image

updated 2020-02-20 09:16:57 -0500

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 09:28:39 -0500 )edit

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

gg gravatar imagegg ( 2020-02-21 11:18:06 -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: 2020-02-20 08:21:09 -0500

Seen: 68 times

Last updated: Feb 20