{{{id=96| v = [plot(sin(x^(1+1/k)), (x,1,10)) for k in [1..5]] /// }}} {{{id=98| A = animate(v); A /// Animation with 5 frames }}} {{{id=97| A.show(delay=50) /// }}} {{{id=104| .show(viewer='canvas3d') # william cauchois /// }}} {{{id=103| graph_editor(graphs.ButterflyGraph()) ///
}}} {{{id=102| /// }}} {{{id=101| /// }}} {{{id=100| /// }}} {{{id=99| /// }}} {{{id=93| factorial? ///

File: /sagenb/flask/sage-4.6.2/local/lib/python2.6/site-packages/sage/functions/other.py

Type: <class ‘sage.functions.other.Function_factorial’>

Definition: factorial(*args, coerce=True, hold=False, dont_call_method_on_arg=False)

Docstring:

Returns the factorial of n.

INPUT:

OUTPUT: an integer or symbolic expression

EXAMPLES:

sage: x = var('x')
sage: factorial(0)
1
sage: factorial(4)
24
sage: factorial(10)
3628800
sage: factorial(6) == 6*5*4*3*2
True
sage: f = factorial(x + factorial(x)); f
factorial(x + factorial(x))
sage: f(x=3)
362880
sage: factorial(x)^2
factorial(x)^2

To prevent automatic evaluation use the hold argument:

sage: factorial(5,hold=True)
factorial(5)

To then evaluate again, we currently must use Maxima via sage.symbolic.expression.Expression.simplify():

sage: factorial(5,hold=True).simplify()
120

We can also give input other than nonnegative integers. For other nonnegative numbers, the gamma() function is used:

sage: factorial(1/2)
1/2*sqrt(pi)
sage: factorial(3/4)
gamma(7/4)
sage: factorial(2.3)
2.68343738195577

But negative input always fails:

sage: factorial(-32)
Traceback (most recent call last):
...
ValueError: factorial -- self = (-32) must be nonnegative

TESTS:

We verify that we can convert this function to Maxima and bring it back into Sage.:

sage: z = var('z')
sage: factorial._maxima_init_()
'factorial'
sage: maxima(factorial(z))
z!
sage: _.sage()
factorial(z)
sage: k = var('k')
sage: factorial(k)
factorial(k)

sage: factorial(3.14)
7.173269190187...

Test latex typesetting:

sage: latex(factorial(x))
x!
sage: latex(factorial(2*x))
\left(2 \, x\right)!
sage: latex(factorial(sin(x)))
\sin\left(x\right)!
sage: latex(factorial(sqrt(x+1)))
\left(\sqrt{x + 1}\right)!
sage: latex(factorial(sqrt(x)))
\sqrt{x}!
sage: latex(factorial(x^(2/3)))
\left(x^{\frac{2}{3}}\right)!

sage: latex(factorial)
{ factorial}
}}} {{{id=94| factorial?? ///

File: /sagenb/flask/sage-4.6.2/local/lib/python2.6/site-packages/sage/functions/other.py

Source Code (starting at line 942):

class Function_factorial(GinacFunction):
    def __init__(self):
        r"""
        Returns the factorial of `n`.

        INPUT:


        -  ``n`` - an integer, or symbolic expression

        -  ``algorithm`` - string (default: 'gmp')

        -  ``'gmp'`` - use the GMP C-library factorial
           function

        -  ``'pari'`` - use PARI's factorial function This
           option has no effect if n is a symbolic expression.


        OUTPUT: an integer or symbolic expression

        EXAMPLES::

            sage: x = var('x')
            sage: factorial(0)
            1
            sage: factorial(4)
            24
            sage: factorial(10)
            3628800
            sage: factorial(6) == 6*5*4*3*2
            True
            sage: f = factorial(x + factorial(x)); f
            factorial(x + factorial(x))
            sage: f(x=3)
            362880
            sage: factorial(x)^2
            factorial(x)^2

        To prevent automatic evaluation use the ``hold`` argument::

            sage: factorial(5,hold=True)
            factorial(5)

        To then evaluate again, we currently must use Maxima via
        :meth:`sage.symbolic.expression.Expression.simplify`::

            sage: factorial(5,hold=True).simplify()
            120

        We can also give input other than nonnegative integers.  For
        other nonnegative numbers, the :func:`gamma` function is used::

            sage: factorial(1/2)
            1/2*sqrt(pi)
            sage: factorial(3/4)
            gamma(7/4)
            sage: factorial(2.3)
            2.68343738195577

        But negative input always fails::

            sage: factorial(-32)
            Traceback (most recent call last):
            ...
            ValueError: factorial -- self = (-32) must be nonnegative

        TESTS:

        We verify that we can convert this function to Maxima and
        bring it back into Sage.::

            sage: z = var('z')
            sage: factorial._maxima_init_()
            'factorial'
            sage: maxima(factorial(z))
            z!
            sage: _.sage()
            factorial(z)
            sage: k = var('k')
            sage: factorial(k)
            factorial(k)

            sage: factorial(3.14)
            7.173269190187...

        Test latex typesetting::

            sage: latex(factorial(x))
            x!
            sage: latex(factorial(2*x))
            \left(2 \, x\right)!
            sage: latex(factorial(sin(x)))
            \sin\left(x\right)!
            sage: latex(factorial(sqrt(x+1)))
            \left(\sqrt{x + 1}\right)!
            sage: latex(factorial(sqrt(x)))
            \sqrt{x}!
            sage: latex(factorial(x^(2/3)))
            \left(x^{\frac{2}{3}}\right)!

            sage: latex(factorial)
            {\rm factorial}
        """
        GinacFunction.__init__(self, "factorial", latex_name='{\rm factorial}',
                conversions=dict(maxima='factorial', mathematica='Factorial'))
}}}

Defining Functions

{{{id=19| def foo(a, bar, w=10): if a: print bar # a block of code that is indented print a, bar, w /// }}} {{{id=18| foo(1, 'abc', 5) /// abc 1 abc 5 }}} {{{id=15| foo(1, 'xyz') /// xyz 1 xyz 10 }}} {{{id=22| foo(bar='gold', a = False, w=3) /// False gold 3 }}} {{{id=23| c = 1; d = 1 def bar(a, b): global d, c c = a; d = b print c, d /// }}} {{{id=76| bar(10,30) /// 10 30 }}} {{{id=75| c, d /// (10, 30) }}} {{{id=78| c = 1; d = 1 def bar(a, b): global d c = a; d = b print c, d x = locals() print 'c' in x, 'd' in x /// }}} {{{id=77| bar(5,10) /// 5 10 True False }}} {{{id=79| /// }}} {{{id=24| bar(5, 10) /// 5 10 }}} {{{id=21| print c, d /// 1 10 }}} {{{id=25| /// }}} {{{id=44| def f(x): import time time.sleep(.05) if int(time.time()) % 2 == 0: return x^2 else: return x^3 /// }}} {{{id=80| plot(f, (x, 1, 10)) /// }}} {{{id=43| f(7) /// 49 }}} {{{id=45| f(7) /// 343 }}}

Symbolic Functions

{{{id=47| f(x,y) = sin(x) + e^cos(y) /// }}} {{{id=81| preparse('f(x,y) = sin(x) + e^cos(y)') /// '__tmp__=var("x,y"); f = symbolic_expression(sin(x) + e**cos(y)).function(x,y)' }}} {{{id=82| /// }}} {{{id=46| f(2,pi) /// e^(-1) + sin(2) }}} {{{id=49| f.integrate(x) /// (x, y) |--> x*e^cos(y) - cos(x) }}} {{{id=50| expand(f^2) /// (x, y) |--> 2*e^cos(y)*sin(x) + sin(x)^2 + e^(2*cos(y)) }}} {{{id=51| plot3d(f, (x,-pi,pi), (y,-2*pi,2*pi), viewer='canvas3d') /// }}} {{{id=14| /// }}}

Call by Reference

{{{id=29| v = [1,2,3] id(v) # random - memory location of v /// 95980576 }}} {{{id=30| def foo(w): print "location of w =", id(w) w.append('hello') print "w =", w /// }}} {{{id=27| foo(v) /// location of w = 95980576 w = [1, 2, 3, 'hello'] }}} {{{id=31| v /// [1, 2, 3, 'hello'] }}} {{{id=32| foo(copy(v)) /// location of w = 69536368 w = [1, 2, 3, 'hello', 'hello'] }}} {{{id=33| v /// [1, 2, 3, 'hello'] }}} {{{id=26| /// }}}

Gotcha: Default Arguments

{{{id=38| def f(a, L=[]): print id(L) L.append(a) print L /// }}} {{{id=39| f(1) /// 92252568 [1] }}} {{{id=40| f(2) /// 92252568 [1, 2] }}} {{{id=41| f(3) /// [1, 2, 3, 3] }}} {{{id=84| def f(a, L=None): if L is None: L = [] L.append(a) print L /// }}} {{{id=83| f(1, ['a', 'b']) /// ['a', 'b', 1] }}} {{{id=85| f(2) /// [2] }}} {{{id=86| f(3) /// [3] }}} {{{id=36| def f(a, L=[]): L.append(a) print L, id(L) /// }}} {{{id=35| f(1) /// [1] 69438424 }}} {{{id=37| f(2) /// [1, 2] 69438424 }}} {{{id=17| f(3) /// [1, 2, 3] 69438424 }}} {{{id=10| /// }}} {{{id=9| /// }}} {{{id=8| /// }}}

Recursion

{{{id=87| def my_factorial(n): if n == 1: return n return n * my_factorial(n-1) /// }}} {{{id=2| my_factorial(20) /// 2432902008176640000 }}} {{{id=3| my_factorial(1000) /// WARNING: Output truncated! full_output.txt Traceback (most recent call last): File "", line 1, in File "_sage_input_53.py", line 10, in exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("bXlfZmFjdG9yaWFsKDEwMDAp"),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))' + '\n', '', 'single') File "", line 1, in File "/tmp/tmpudCZle/___code___.py", line 3, in exec compile(u'my_factorial(_sage_const_1000 )' + '\n', '', 'single') File "", line 1, in File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial ... return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 6, in my_factorial return n * my_factorial(n-_sage_const_1 ) File "/tmp/tmpiCNr3F/___code___.py", line 4, in my_factorial if n == _sage_const_1 : RuntimeError: maximum recursion depth exceeded in cmp }}} {{{id=4| import sys sys.getrecursionlimit() /// 1000 }}} {{{id=5| sys.setrecursionlimit(1000000) /// }}} {{{id=92| /// }}} {{{id=6| a = my_factorial(1000) /// }}} {{{id=88| %time a = my_factorial(10^5) /// /sagenb/flask/sage-4.6.2/local/bin/sage-sage: line 449: 11391 Segmentation fault python "$@" }}} {{{id=90| time b = factorial(10^5) /// Time: CPU 0.04 s, Wall: 0.04 s }}} {{{id=89| time c = prod([1..10^4]) /// Time: CPU 0.02 s, Wall: 0.01 s }}} {{{id=91| prod?? /// }}} {{{id=52| /// }}}

Classes

{{{id=7| class MyClass: """A simple example class.""" # A Python object attribute; this is basically a default # piece of data that is available to each instance of the # class, but can be changed in the instance without changing # it in the class. (See example below.) i = 12345 # A function attribute. Again, this is available to each # instance, and can be changed. def f(self): return 'hello world' /// }}} {{{id=54| MyClass /// }}} {{{id=105| id(MyClass) /// 69401872 }}} {{{id=57| MyClass.i /// 12345 }}} {{{id=56| MyClass.f /// }}} {{{id=60| MyClass.__doc__ /// 'A simple example class.' }}} {{{id=107| MyClass /// }}} {{{id=106| MyClass() /// <__main__.MyClass instance at 0x4251a28> }}} {{{id=59| x = MyClass(); x /// <__main__.MyClass instance at 0x42517e8> }}} {{{id=63| x.f() /// 'hello world' }}} {{{id=58| x.i /// 12345 }}} {{{id=61| x.i = 50 /// }}} {{{id=64| def g(): return "goodbye" x.f = g x.f() /// 'goodbye' }}} {{{id=62| y = MyClass(); y.i /// 12345 }}} {{{id=55| y.f() /// 'hello world' }}} {{{id=74| def g(self): return "goodbye" MyClass.f = g /// }}} {{{id=73| y = MyClass() y.f() /// 'goodbye' }}} {{{id=66| /// }}}

The next example illustrates how to use self and several "dunder" (=double underscore) methods:

{{{id=65| class Number: def __init__(derreck, x): # called when Number is instantiated derreck.x = x def __repr__(self): # defines how Number prints return "** The Number %s ** !!!"%self.x def __add__(self, right): # defines how "+" works return Number(self.x + right.x) /// }}} {{{id=108| Number /// }}} {{{id=109| Number(37) /// ** The Number 37 ** !!! }}} {{{id=111| v = [Number(37), Number(40)] v /// [** The Number 37 ** !!!, ** The Number 40 ** !!!] }}} {{{id=69| n = Number(37) n.x /// 37 }}} {{{id=71| n /// The Number 37 }}} {{{id=70| n + Number(15) /// The Number 52 }}} {{{id=72| class Shape: pass class Triangle(Shape): def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __repr__(self): return "triangle with sides (%s,%s,%s)"%(self.a, self.b, self.c) def area(self): return self.a*self.b*self.c/2 #WRONG class EqualateralTriangle(Triangle): def __init__(self, a): Triangle.__init__(self, a, a, a) /// }}} {{{id=112| et = EqualateralTriangle(7); et /// triangle with sides (7,7,7) }}} {{{id=118| et.area() /// 343/2 }}} {{{id=113| EqualateralTriangle.__repr__(et) /// 'triangle with sides (7,7,7)' }}} {{{id=114| 'Hello %s; you are %s'%("Derreck", 7/8) /// 'Hello Derreck; you are 7/8' }}} {{{id=115| "ksfj " + 'asklj' /// 'ksfj asklj' }}} {{{id=116| 'Hello '+'Derreck' +'; you are '+str(7/8) /// 'Hello Derreck; you are 7/8' }}} {{{id=117| QQ /// Rational Field }}} {{{id=119| type(QQ) /// }}} {{{id=120| QQ.random_element() /// 1/10 }}} {{{id=121| type(3/4) /// }}} {{{id=122| VectorSpaces(QQ) /// Category of vector spaces over Rational Field }}} {{{id=123| /// }}}