Sage入门指南之一概览

514 days ago by z295474566

 

数学软件Sage入门指南之一:

概  览


Sage是一个可以进行代数、几何、数论、密码学、数值计算及相关领域的研究和教学的自由开源数学软件。Sage开发模型和Sage本身的技术都非常突出地强调开放、社区、协作和合作:我们是在造车,而不是在重复发明轮子。Sage总的目标是建立一个替代Maple、Mathematica 、Magma和MATLAB的可用的自由开源软件。

本入门指南使你在几小时内熟悉Sage。

尽 管Sage的大部分是通过Python实现的,没有Python背景的读者也可阅读本教程。也许你啥时候想学学Python(一个非常有趣的语言!),那 么网上有很多极好的免费资源让你学,比如[PyT] 和 [Dive]。如果你只想赶快试试Sage,本教程就是你起步的地方。

安装

如果你不想在电脑上装Sage,只想试一些命令,可以到http://www.sagenb.org用在线版。否则就到Sage主页上文档的Sage安装指南部分看怎么把Sage安装到你电脑上的介绍去吧。这里我只讲两句题外话。

1. 下载的Sage文件都是“内装电池?鬼使神差?”的。换句话说,虽然Sage使用Python , IPython ,PARI,GAP,Singular,Maxima,NTL,GMP等等,但你不需要一个一个地去装,它们都含在Sage的发行版中。但是要使用某些Sage的功 能,比如Macaulay或KASH ,则必须安装相关的可选软件包,或者至少你的计算机上安装了相关的程序。Macaulay和KASH是用来列出可用的可选软件包的Sage包(键入 sage -optional,或浏览Sage网站上的“下载”页)。

2.Sage的预编译二进制版本(可在Sage网站获得)比源码版安装便捷。只要将文件解解压就可以run了。

使用Sage的几种方法

你可以通过下面几种途径使用Sage。

Notebook图形界面:你可以到参考手册上看Notebook的之章或者本教程下面的Notebook部分;

交互式命令行:参见交互Shell一章;

编程:在Sage中编写解释和编译程序(见加载和加附Sage文件和生成编译代码章节);及

脚本:通过编写使用Sage库的独立Python脚本(见独立Python/Sage脚本一章)。

Sage的长远目标

有用:Sage的应用对象是学数学的学生(从高中到研究生院) ,教师和搞研究的数学家。目的是提供可用于探索和研究代数,几何,数论,微积分,数值计算等数学结构的软件,Sage可以更容易地对数学对象进行交互实验。

高效率:速度。Sage使用像GMP,PARI,GAP和NTL这样的高度优化的成熟软件,所以某些操作是非常之快的。

自 由和开放源码:源代码必须免费并具有可读性,使用户可以了解系统到底在干什么,从而更容易扩展。就像数学家通过细读或浏览证明来深入了解一个定理一样,做 计算的人应该能够通过阅读源代码的方式了解计算如何进行。如果你发布的文章采用Sage做计算,你可以放心,你的读者将始终能够自由获得Sage和它所有 的源代码,你甚至可以将你使用的Sage存档并重新发布版本。

轻松编译:不管是Linux , OS X还是Windows用户都应该可以很容易地从源代码编译Sage。以使用户可以在更改系统时更具灵活性。

合作:提供对包括PARI,GAP,Singular,Maxima,KASH,Magma,Maple, 和Mathematica在内的大多数计算机数学套件的强大接口口。Sage的目的是统一和扩大现有的数学软件。

有案可查:带有许多实例及关于其背后的数学的讨论的“入门指南”,“编程指南”,“参考手册”和“如何实现...”。

可扩展性:能够定义新的数据类型和内置类型扩展,并支持多种语言。

友好:用户应该可以很容易地了解给定对象的功能并查看文件和源代码。并实现了高度的用户支持。

让我们先来感受一下Sage吧。

2 + 2*e+pi 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\pi + 2 \, e + 2
\newcommand{\Bold}[1]{\mathbf{#1}}\pi + 2 \, e + 2
factor(-2010) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}-1 \cdot 2 \cdot 3 \cdot 5 \cdot 67
\newcommand{\Bold}[1]{\mathbf{#1}}-1 \cdot 2 \cdot 3 \cdot 5 \cdot 67
A = matrix(3,4, range(12)); A 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rrrr}
0 & 1 & 2 & 3 \\
4 & 5 & 6 & 7 \\
8 & 9 & 10 & 11
\end{array}\right)
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rrrr}
0 & 1 & 2 & 3 \\
4 & 5 & 6 & 7 \\
8 & 9 & 10 & 11
\end{array}\right)
B=Matrix(3,2,[1,0,0,0,1,0]);B 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rr}
1 & 0 \\
0 & 0 \\
1 & 0
\end{array}\right)
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rr}
1 & 0 \\
0 & 0 \\
1 & 0
\end{array}\right)
C=Matrix([[1,2,3],[3,2,1],[1,1,1]]);C[2,2] 
       
\newcommand{\Bold}[1]{\mathbf{#1}}1
\newcommand{\Bold}[1]{\mathbf{#1}}1
V=vector([0,1,2]);V[2] 
       
\newcommand{\Bold}[1]{\mathbf{#1}}2
\newcommand{\Bold}[1]{\mathbf{#1}}2
factor(A.charpoly()) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}x^{2} \cdot (x^{2} - 30x - 80)
\newcommand{\Bold}[1]{\mathbf{#1}}x^{2} \cdot (x^{2} - 30x - 80)
sage: m = matrix(ZZ,2, range(4)) sage: m[0,0] = m[0,0] - 3 sage: m 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rr}
-3 & 1 \\
2 & 3
\end{array}\right)
\newcommand{\Bold}[1]{\mathbf{#1}}\left(\begin{array}{rr}
-3 & 1 \\
2 & 3
\end{array}\right)
sage: E = EllipticCurve([1,2,3,4,5]); sage: E 
       
\newcommand{\Bold}[1]{\mathbf{#1}}y^2 + xy + 3y = x^3 + 2x^2 + 4x + 5 
\newcommand{\Bold}[1]{\mathbf{#1}}y^2 + xy + 3y = x^3 + 2x^2 + 4x + 5 
E.anlist(10) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[0, 1, 1, 0, -1, -3, 0, -1, -3, -3, -3\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[0, 1, 1, 0, -1, -3, 0, -1, -3, -3, -3\right]
E.rank() 
       
\newcommand{\Bold}[1]{\mathbf{#1}}1
\newcommand{\Bold}[1]{\mathbf{#1}}1
k = 1/(sqrt(3)*I + 3/4 + sqrt(73)*5/9); print k 
       
1/(I*sqrt(3) + 5/9*sqrt(73) + 3/4)
1/(I*sqrt(3) + 5/9*sqrt(73) + 3/4)
       
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{i \, \sqrt{3} + \frac{5}{9} \, \sqrt{73} + \frac{3}{4}}
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{i \, \sqrt{3} + \frac{5}{9} \, \sqrt{73} + \frac{3}{4}}
latex(k) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{\frac{1}{i \, \sqrt{3} + \frac{5}{9} \, \sqrt{73} + \frac{3}{4}}}
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{\frac{1}{i \, \sqrt{3} + \frac{5}{9} \, \sqrt{73} + \frac{3}{4}}}
N(k) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}0.165495678130644 - 0.0521492082074256i
\newcommand{\Bold}[1]{\mathbf{#1}}0.165495678130644 - 0.0521492082074256i
sage: N(k,30) # 30 "bits" 
       
\newcommand{\Bold}[1]{\mathbf{#1}}0.16549568 - 0.052149208i
\newcommand{\Bold}[1]{\mathbf{#1}}0.16549568 - 0.052149208i
 
       
 赋值、等式和运算

除了少数情况外,Sage使用Python语言,因此关于Python的大多数介绍性书籍对学习Sage都有帮助。

Sage使用=赋值,使用== , <= , > = , < 和 >进行比较。请看例子:

a=7;a 
       
\newcommand{\Bold}[1]{\mathbf{#1}}7
\newcommand{\Bold}[1]{\mathbf{#1}}7
3==2 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm False}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm False}
3>2 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
x=0;x+=1;x 
       
\newcommand{\Bold}[1]{\mathbf{#1}}1
\newcommand{\Bold}[1]{\mathbf{#1}}1
x=2;x**=2;x 
       
\newcommand{\Bold}[1]{\mathbf{#1}}4
\newcommand{\Bold}[1]{\mathbf{#1}}4
x=[123,'xyz'];x+=[011];x#列表也支持增量赋值 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[123, \hbox{xyz}, 9\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[123, \hbox{xyz}, 9\right]
x,y,z=1,2,3 print x,y,z 
       
1 2 3
1 2 3
x=666;y=888; x,y=y,x;#多远赋值使得数据交换更灵活 print "x=",x print "y=",y 
       
x= 888
y= 666
x= 888
y= 666
 
       

基本数学运算

Sage提供全部的基本数学运算:

2**3 # ** 表示幂运算 
       
\newcommand{\Bold}[1]{\mathbf{#1}}8
\newcommand{\Bold}[1]{\mathbf{#1}}8
2^3 # ^ 是 ** 的同义符(与Python不同) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}8
\newcommand{\Bold}[1]{\mathbf{#1}}8
10 % 3 # 对于整数而言 % 表示取模,即求余 
       
\newcommand{\Bold}[1]{\mathbf{#1}}1
\newcommand{\Bold}[1]{\mathbf{#1}}1
10/4 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{5}{2}
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{5}{2}
10//4 # 对于整数 // 返回整数商 
       
\newcommand{\Bold}[1]{\mathbf{#1}}2
\newcommand{\Bold}[1]{\mathbf{#1}}2
4 * (10 // 4) + 10 % 4 == 10 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
3^2*4 + 2%5 
       
\newcommand{\Bold}[1]{\mathbf{#1}}38
\newcommand{\Bold}[1]{\mathbf{#1}}38

3^2*4 + 2%5这样的表达式的计算取决于运算符的顺序,其于A.1节中的“运算符排名表”中指定。

Sage同样提供一些常用的数学函数;下面是一些例子:

sqrt(3.4) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}1.84390889145858
\newcommand{\Bold}[1]{\mathbf{#1}}1.84390889145858
sin(5.135) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}-0.912021158525540
\newcommand{\Bold}[1]{\mathbf{#1}}-0.912021158525540
sin(pi/3) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{2} \, \sqrt{3}
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{2} \, \sqrt{3}

最后的例子表明,某些数学表达式返回“准确”值,而不是数值逼近。要获得数值逼近,可使用n函数或n方法(两者有个更长的名称, numerical_approx ,函数N的功能与n相同) 。其采取可选参数prec或digits来指定输出二进制精度或十进制精度的位数,默认的精度是53位二进制。

exp(2) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}e^{2}
\newcommand{\Bold}[1]{\mathbf{#1}}e^{2}
n(exp(2)) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}7.38905609893065
\newcommand{\Bold}[1]{\mathbf{#1}}7.38905609893065
sqrt(pi).numerical_approx() 
       
\newcommand{\Bold}[1]{\mathbf{#1}}1.77245385090552
\newcommand{\Bold}[1]{\mathbf{#1}}1.77245385090552
sin(10).n(digits=5) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}-0.54402
\newcommand{\Bold}[1]{\mathbf{#1}}-0.54402
N(sin(10),digits=10) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}-0.5440211109
\newcommand{\Bold}[1]{\mathbf{#1}}-0.5440211109
numerical_approx(pi, prec=200) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}3.1415926535897932384626433832795028841971693993751058209749
\newcommand{\Bold}[1]{\mathbf{#1}}3.1415926535897932384626433832795028841971693993751058209749

数据类型

Python是动态类型的,因此,提交给每个变量的值都有一个关联的类型,但某个变量的值可能是特定范围内的任何Python数据类型:

a = 5 # a是一个整数 
       
type(a) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'sage.rings.integer.Integer' > }
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'sage.rings.integer.Integer' > }
a = 5/3 # 现在a是一个有理数 
       
type(a) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'sage.rings.rational.Rational' > }
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'sage.rings.rational.Rational' > }
a = 'hello' # 现在a是一个字符串 
       
type(a) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'str' > }
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{ < type 'str' > }

与此不同,C语言是静态类型的;一个变量被声明为int就只能容纳一个int值。

在Python中以0开头的整数被视为八进制数,也就是以8为基数的数,这是造成混淆的一个潜在的根源。

011 
       
\newcommand{\Bold}[1]{\mathbf{#1}}9
\newcommand{\Bold}[1]{\mathbf{#1}}9
8 + 1 
       
\newcommand{\Bold}[1]{\mathbf{#1}}9
\newcommand{\Bold}[1]{\mathbf{#1}}9
n = 011 
       
n.str(8) # 以8为基数的n的字符串表示形式 
       
\newcommand{\Bold}[1]{\mathbf{#1}}11
\newcommand{\Bold}[1]{\mathbf{#1}}11

这与C语言一致。

获取帮助

Sage有大量的内建文档,可通过在键入的函数名或常量后面加一个问号查看:

tan? 
       

File: /usr/local/sage2/local/lib/python2.6/site-packages/sage/functions/trig.py

Type: <class ‘sage.functions.trig.Function_tan’>

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

Docstring:

The tangent function

EXAMPLES:

sage: tan(pi)
0
sage: tan(3.1415)
-0.0000926535900581913
sage: tan(3.1415/4)
0.999953674278156
sage: tan(pi/4)
1
sage: tan(1/2)
tan(1/2)
sage: RR(tan(1/2))
0.546302489843790

File: /usr/local/sage2/local/lib/python2.6/site-packages/sage/functions/trig.py

Type: <class ‘sage.functions.trig.Function_tan’>

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

Docstring:

The tangent function

EXAMPLES:

sage: tan(pi)
0
sage: tan(3.1415)
-0.0000926535900581913
sage: tan(3.1415/4)
0.999953674278156
sage: tan(pi/4)
1
sage: tan(1/2)
tan(1/2)
sage: RR(tan(1/2))
0.546302489843790
log2? 
       

File: /usr/local/sage2/local/lib/python2.6/site-packages/sage/categories/commutative_rings.py

Type: <type 'sage.symbolic.expression.Expression'>

Definition: log2(*args, **kwds)

Docstring:


x.__init__(...) initializes x; see x.__class__.__doc__ for signature

File: /usr/local/sage2/local/lib/python2.6/site-packages/sage/categories/commutative_rings.py

Type: <type 'sage.symbolic.expression.Expression'>

Definition: log2(*args, **kwds)

Docstring:


x.__init__(...) initializes x; see x.__class__.__doc__ for signature
log?? 
       

File: /usr/local/sage2/local/lib/python2.6/site-packages/sage/functions/log.py

Source Code (starting at line 170):

def log(x, base=None):
    """
    Return the logarithm of x to the given base.

    Calls the ``log`` method of the object x when computing
    the logarithm, thus allowing use of logarithm on any object
    containing a ``log`` method. In other words, log works
    on more than just real numbers.

    EXAMPLES::

        sage: log(e^2)
        2
        sage: log(1024, 2); RDF(log(1024, 2))
        10
        10.0
        sage: log(10, 4); RDF(log(10, 4))
        log(10)/log(4)
        1.66096404744

    ::

        sage: log(10, 2)
        log(10)/log(2)
        sage: n(log(10, 2))
        3.32192809488736
        sage: log(10, e)
        log(10)
        sage: n(log(10, e))
        2.30258509299405

    The log function works for negative numbers, complex
    numbers, and symbolic numbers too, picking the branch
    with angle between `-pi` and `pi`::

        sage: log(-1+0*I)
        I*pi
        sage: log(CC(-1))
        3.14159265358979*I
        sage: log(-1.0)
        3.14159265358979*I

    For input zero, the following behavior occurs::

        sage: log(0)
        -Infinity
        sage: log(CC(0))
        -infinity
        sage: log(0.0)
        -infinity

    The log function also works in finite fields as long as the base is
    generator of the multiplicative group::

        sage: F = GF(13); g = F.multiplicative_generator(); g
        2
        sage: a = F(8)
        sage: log(a,g); g^log(a,g)
        3
        8
        sage: log(a,3)
Traceback (click to the left of this block for traceback)
...
                                
                            

File: /usr/local/sage2/local/lib/python2.6/site-packages/sage/functions/log.py

Source Code (starting at line 170):

def log(x, base=None):
    """
    Return the logarithm of x to the given base.

    Calls the ``log`` method of the object x when computing
    the logarithm, thus allowing use of logarithm on any object
    containing a ``log`` method. In other words, log works
    on more than just real numbers.

    EXAMPLES::

        sage: log(e^2)
        2
        sage: log(1024, 2); RDF(log(1024, 2))
        10
        10.0
        sage: log(10, 4); RDF(log(10, 4))
        log(10)/log(4)
        1.66096404744

    ::

        sage: log(10, 2)
        log(10)/log(2)
        sage: n(log(10, 2))
        3.32192809488736
        sage: log(10, e)
        log(10)
        sage: n(log(10, e))
        2.30258509299405

    The log function works for negative numbers, complex
    numbers, and symbolic numbers too, picking the branch
    with angle between `-pi` and `pi`::

        sage: log(-1+0*I)
        I*pi
        sage: log(CC(-1))
        3.14159265358979*I
        sage: log(-1.0)
        3.14159265358979*I

    For input zero, the following behavior occurs::

        sage: log(0)
        -Infinity
        sage: log(CC(0))
        -infinity
        sage: log(0.0)
        -infinity

    The log function also works in finite fields as long as the base is
    generator of the multiplicative group::

        sage: F = GF(13); g = F.multiplicative_generator(); g
        2
        sage: a = F(8)
        sage: log(a,g); g^log(a,g)
        3
        8
        sage: log(a,3)
        Traceback (most recent call last):
        ...
        ValueError: base (=3) for discrete log must generate multiplicative group

    The log function also works for p-adics (see documentation for
    p-adics for more information)::

        sage: R = Zp(5); R
        5-adic Ring with capped relative precision 20
        sage: a = R(16); a
        1 + 3*5 + O(5^20)
        sage: log(a)
        3*5 + 3*5^2 + 3*5^4 + 3*5^5 + 3*5^6 + 4*5^7 + 2*5^8 + 5^9 + 5^11 + 2*5^12 + 5^13 + 3*5^15 + 2*5^16 + 4*5^17 + 3*5^18 + 3*5^19 + O(5^20)
    """
    if base is None:
        try:
            return x.log()
        except AttributeError:
            return ln(x)
    else:
        try:
            return x.log(base)
        except (AttributeError, TypeError):
            return log(x) / log(base)
search_doc("rgbcolor") 
       
Warning, the following Sage documentation hasn't been built,
so documentation search results may be incomplete:

/usr/local/sage2/devel/sage/doc/output/html/en/thematic_tutorials
/usr/local/sage2/devel/sage/doc/output/html/en/faq

You can build these with 'sage -docbuild DOCUMENT html',
where DOCUMENT is one of 'thematic_tutorials', 'faq', 
or you can use 'sage -docbuild all html' to build all of the missing
documentation.

Search Documentation: "rgbcolor"

  1. bordeaux_2008/elliptic_curves.html
  2. constructions/calculus.html
  3. constructions/plotting.html
  4. reference/sage/calculus/calculus.html
  5. reference/sage/combinat/iet/iet.html
  6. reference/sage/combinat/words/paths.html
  7. reference/sage/functions/piecewise.html
  8. reference/sage/groups/perm_gps/cubegroup.html
  9. reference/sage/plot/animate.html
  10. reference/sage/plot/arrow.html
  11. reference/sage/plot/bar_chart.html
  12. reference/sage/plot/bezier_path.html
  13. reference/sage/plot/circle.html
  14. reference/sage/plot/disk.html
  15. reference/sage/plot/line.html
  16. reference/sage/plot/plot.html
  17. reference/sage/plot/plot3d/platonic.html
  18. reference/sage/plot/plot3d/shapes2.html
  19. reference/sage/plot/point.html
  20. reference/sage/plot/polygon.html
  21. reference/sage/plot/primitive.html
  22. reference/sage/plot/step.html
  23. reference/sage/plot/text.html
  24. reference/sage/rings/arith.html
  25. reference/sage/rings/padics/padic_base_generic.html
  26. reference/sage/rings/polynomial/groebner_fan.html
  27. reference/sage/rings/polynomial/polynomial_element.html
  28. reference/sage/schemes/elliptic_curves/ell_finite_field.html
  29. reference/sage/schemes/elliptic_curves/ell_generic.html
  30. reference/sage/schemes/elliptic_curves/ell_point.html
  31. reference/sage/schemes/elliptic_curves/heegner.html
  32. reference/sage/symbolic/expression.html
  33. reference/sagenb/notebook/interact.html
  34. tutorial/tour_algebra.html
  35. tutorial/tour_plotting.html
  36. tutorial/tour_algebra.html
  37. tutorial/tour_plotting.html
Warning, the following Sage documentation hasn't been built,
so documentation search results may be incomplete:

/usr/local/sage2/devel/sage/doc/output/html/en/thematic_tutorials
/usr/local/sage2/devel/sage/doc/output/html/en/faq

You can build these with 'sage -docbuild DOCUMENT html',
where DOCUMENT is one of 'thematic_tutorials', 'faq', 
or you can use 'sage -docbuild all html' to build all of the missing documentation.

Search Documentation: "rgbcolor"

  1. bordeaux_2008/elliptic_curves.html
  2. constructions/calculus.html
  3. constructions/plotting.html
  4. reference/sage/calculus/calculus.html
  5. reference/sage/combinat/iet/iet.html
  6. reference/sage/combinat/words/paths.html
  7. reference/sage/functions/piecewise.html
  8. reference/sage/groups/perm_gps/cubegroup.html
  9. reference/sage/plot/animate.html
  10. reference/sage/plot/arrow.html
  11. reference/sage/plot/bar_chart.html
  12. reference/sage/plot/bezier_path.html
  13. reference/sage/plot/circle.html
  14. reference/sage/plot/disk.html
  15. reference/sage/plot/line.html
  16. reference/sage/plot/plot.html
  17. reference/sage/plot/plot3d/platonic.html
  18. reference/sage/plot/plot3d/shapes2.html
  19. reference/sage/plot/point.html
  20. reference/sage/plot/polygon.html
  21. reference/sage/plot/primitive.html
  22. reference/sage/plot/step.html
  23. reference/sage/plot/text.html
  24. reference/sage/rings/arith.html
  25. reference/sage/rings/padics/padic_base_generic.html
  26. reference/sage/rings/polynomial/groebner_fan.html
  27. reference/sage/rings/polynomial/polynomial_element.html
  28. reference/sage/schemes/elliptic_curves/ell_finite_field.html
  29. reference/sage/schemes/elliptic_curves/ell_generic.html
  30. reference/sage/schemes/elliptic_curves/ell_point.html
  31. reference/sage/schemes/elliptic_curves/heegner.html
  32. reference/sage/symbolic/expression.html
  33. reference/sagenb/notebook/interact.html
  34. tutorial/tour_algebra.html
  35. tutorial/tour_plotting.html
  36. tutorial/tour_algebra.html
  37. tutorial/tour_plotting.html

自动补全

Sage提供“Tab自动补全”功能:输入一个函数的前几个字母后按tab键。例如,如果在键入ta后按TAB,Sage会列印出tachyon,tan,tanh,taylor。这是一个在Sage中查询函数名和其它结构的很好途径。

函数的定义

在Sage中定义函数使用def命令,并在变量参数列表后加一个冒号。例如:

def is_even(n): return n%2 == 0 
       
is_even(2) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
is_even(3) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm False}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm False}

参数

不要指明任何参数的类型。可以指明多个参数,每个参数也可以给定可选的默认值。例如,下面定义的函数如果在使用中不给出divisor的值,函数会默认divisor=2。

def is_divisible_by(number, divisor=2): return number%divisor == 0 
       
is_divisible_by(6,2) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
is_divisible_by(6) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
is_divisible_by(6, 5) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm False}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm False}

在调用函数时也可以明确指定一个或每个输入参数的值;在明确指定时,参数的顺序可以是任意的:

is_divisible_by(6, divisor=5) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm False}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm False}
is_divisible_by(divisor=2, number=6) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}
\newcommand{\Bold}[1]{\mathbf{#1}}{\rm True}

缩进

在Python中不像其他函数那样采用花括号或begin和end块来指示代码块。而是以缩进表示代码块,因此缩进一定要匹配。

def even(n): v = [] for i in range(3,n): if i % 2 == 0: v.append(i) return v 
       
even(10) 
       
[4, 6, 8]
[4, 6, 8]

行末的分号不是必须的,新一行的开始也表示上一行的结束。如果在一行中有多个语句,则每条语句必须以分号分开:

a = 5; b = a + 3; c = b^2; c 
       
64
64

如果想将一行代码分为多行,可使用反斜线断行:

2+\ 3 
       
5
5

在Sage中通过一列整数的迭代来计数。例如,下面的第一行等价于C++或Jave中的for(i=0; i<3; i++):

for i in range(3): print i 
       
0
1
2
0
1
2

下面的第一行等同于for(i=2;i<5;i++)。

for i in range(2,5): print i 
       
2
3
4
2
3
4

第三个参数控制步进值,因此下面的代码等同于for(i=1;i<6;i+=2)。

for i in range(1,6,2): print i 
       
1
3
5
1
3
5

格式化字符串

在Sage中经常需要为显示运算出的数字列印数表。简单点的办法是使用格式化字符串。下面代码产生了一个列距为10的平方值立方值三列表。

for i in range(5): print '%10s %10s %10s' %(i, i^2, i^3) 
       
         0          0          0
         1          1          1
         2          4          8
         3          9         27
         4         16         64
         0          0          0
         1          1          1
         2          4          8
         3          9         27
         4         16         64

列表

Sage中最基础的数据结构是列表--正如其名--一个任意对象的列表。例如前面用过的range即产生一个列表:

range(3,10) 
       
[3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]

下面是一个更复杂的列表:

v = [1, "hello", 2/3, sin(x^3)] v 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[1, \hbox{hello}, \frac{2}{3}, \sin\left(x^{3}\right)\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[1, \hbox{hello}, \frac{2}{3}, \sin\left(x^{3}\right)\right]

和很多语言一样,列表的索引以0开始。

v[0] 
       
\newcommand{\Bold}[1]{\mathbf{#1}}1
\newcommand{\Bold}[1]{\mathbf{#1}}1
v[3] 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\sin\left(x^{3}\right)
\newcommand{\Bold}[1]{\mathbf{#1}}\sin\left(x^{3}\right)

用len(v)可获得v的长度,用v.append(obj)可将一个新的对象追加到v的末尾,用del v[i]可以删掉v的第i项:

len(v) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}4
\newcommand{\Bold}[1]{\mathbf{#1}}4
v.append(1.5);v 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[1, \hbox{hello}, \frac{2}{3}, \sin\left(x^{3}\right), 1.50000000000000\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[1, \hbox{hello}, \frac{2}{3}, \sin\left(x^{3}\right), 1.50000000000000\right]
del v[1];v 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[1, \frac{2}{3}, \sin\left(x^{3}\right), 1.50000000000000\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[1, \frac{2}{3}, \sin\left(x^{3}\right), 1.50000000000000\right]

字典

另外一个重要的数据结构是字典(或关联列)。除了可以用几乎任何对象作为索引外(索引不可更改),它与列表一样:

d = {'hi':-2, 3/8:pi, e:pi} d['hi'] 
       
\newcommand{\Bold}[1]{\mathbf{#1}}-2
\newcommand{\Bold}[1]{\mathbf{#1}}-2
d[e] 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\pi
\newcommand{\Bold}[1]{\mathbf{#1}}\pi
d[3/8] 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\pi
\newcommand{\Bold}[1]{\mathbf{#1}}\pi

可以使用类来定义新的数据类型。用类封装数学对象是个强大的技术,可以帮助简化和组织Sage程序。在下面的代码中,由内置类型list派生的类可表示n以内的偶数列。

class Evens(list): def __init__(self, n): self.n = n list.__init__(self, range(2, n+1, 2)) def __repr__(self): return "Even positive numbers up to n." 
       

调用__inti__方法可在实例创建时进行初始化;__repr__方法会将对象列印出来。我们称第二行的__init__方法为构造函数。用下面的代码创建Evens类的实例。

e = Evens(10) e 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{Even positive numbers up to n.}
\newcommand{\Bold}[1]{\mathbf{#1}}\hbox{Even positive numbers up to n.}

注意调用e时使用之前定义的__repr__方法进行了列印。要看到潜藏的数列,使用list函数。

list(e) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[2, 4, 6, 8, 10\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[2, 4, 6, 8, 10\right]

我们也可以看到e的n属性及将其看待成一个列表。

e.n 
       
\newcommand{\Bold}[1]{\mathbf{#1}}10
\newcommand{\Bold}[1]{\mathbf{#1}}10
e[4] 
       
\newcommand{\Bold}[1]{\mathbf{#1}}10
\newcommand{\Bold}[1]{\mathbf{#1}}10

Sage可以进行各种基本代数和微积分的计算:例如,方程式求解,微分,积分,拉普拉斯变换。可到“Sage构建”文档查看更多实例。


sage: x = var('x') sage: solve(x^2 + 3*x + 2, x) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[x = \left(-2\right), x = \left(-1\right)\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[x = \left(-2\right), x = \left(-1\right)\right]

可以求解方程式中几个变量中的一个:

x, b, c = var('x b c') solve([x^2 + b*x + c == 0],x) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[x = -\frac{1}{2} \, b - \frac{1}{2} \, \sqrt{b^{2} - 4 \, c}, x = -\frac{1}{2} \, b + \frac{1}{2} \, \sqrt{b^{2} - 4 \, c}\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[x = -\frac{1}{2} \, b - \frac{1}{2} \, \sqrt{b^{2} - 4 \, c}, x = -\frac{1}{2} \, b + \frac{1}{2} \, \sqrt{b^{2} - 4 \, c}\right]

也可进行多变量求解:

x, y = var('x, y') solve([x+y==6, x-y==4], x, y) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[\left[x = 5, y = 1\right]\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[\left[x = 5, y = 1\right]\right]

下面是Jason Grout提供的一个使用Sage求解非线性方程组的例子:首先求出方程组的符号解:

x,y,p,q=var('x y p q') eq1 = p+q==9 eq2 = q*y+p*x==-6 eq3 = q*y^2+p*x^2==24 solve([eq1,eq2,eq3,p==1],p,q,x,y) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[\left[p = 1, q = 8, x = -\frac{4}{3} \, \sqrt{10} - \frac{2}{3}, y = \frac{1}{6} \, \sqrt{2} \sqrt{5} - \frac{2}{3}\right], \left[p = 1, q = 8, x = \frac{4}{3} \, \sqrt{10} - \frac{2}{3}, y = -\frac{1}{6} \, \sqrt{2} \sqrt{5} - \frac{2}{3}\right]\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[\left[p = 1, q = 8, x = -\frac{4}{3} \, \sqrt{10} - \frac{2}{3}, y = \frac{1}{6} \, \sqrt{2} \sqrt{5} - \frac{2}{3}\right], \left[p = 1, q = 8, x = \frac{4}{3} \, \sqrt{10} - \frac{2}{3}, y = -\frac{1}{6} \, \sqrt{2} \sqrt{5} - \frac{2}{3}\right]\right]

如果想求数值近似解,则可用下面的代码:(函数n列印出解的数值近似,其参数是该数值的比特精度。)

solns = solve([eq1,eq2,eq3,p==1],p,q,x,y, solution_dict=True) [[s[p].n(30), s[q].n(30), s[x].n(30), s[y].n(30)] for s in solns] 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[\left[1.0000000, 8.0000000, -4.8830369, -0.13962039\right], \left[1.0000000, 8.0000000, 3.5497035, -1.1937129\right]\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[\left[1.0000000, 8.0000000, -4.8830369, -0.13962039\right], \left[1.0000000, 8.0000000, 3.5497035, -1.1937129\right]\right]

方程式求数值解

有时solve函数可能无法求出方程式的确切解。如果求不出,可以用find_root函数去求它的数值解。例如,下面的等式返回的结果不是我们想要的:

theta = var('theta') solve(cos(theta)==sin(theta),theta) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\left[\sin\left(\theta\right) = \cos\left(\theta\right)\right]
\newcommand{\Bold}[1]{\mathbf{#1}}\left[\sin\left(\theta\right) = \cos\left(\theta\right)\right]

反过来,我们用find_root可对上面的等式求得一个在0<theta<pi/2间的解:

find_root(cos(theta)==sin(theta),0,pi/2) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}0.785398163397
\newcommand{\Bold}[1]{\mathbf{#1}}0.785398163397

微分、积分

Sage可以对很多方程求导或积分。例如,下面代码就是\sin(u)u求导:

u = var('u') diff(sin(u), u) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\cos\left(u\right)
\newcommand{\Bold}[1]{\mathbf{#1}}\cos\left(u\right)

计算\sin(x^2)的四阶导数:

sage: x = var('x') sage: diff(sin(x^2),x,4) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}16 \, x^{4} \sin\left(x^{2}\right) - 48 \, x^{2} \cos\left(x^{2}\right) - 12 \, \sin\left(x^{2}\right)
\newcommand{\Bold}[1]{\mathbf{#1}}16 \, x^{4} \sin\left(x^{2}\right) - 48 \, x^{2} \cos\left(x^{2}\right) - 12 \, \sin\left(x^{2}\right)

x^2 + 17*y^2分别对xy偏导:

x, y = var('x,y') f = x^2 + 17*y^2 f.diff(x) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}2 \, x
\newcommand{\Bold}[1]{\mathbf{#1}}2 \, x
f.diff(y) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}34 \, y
\newcommand{\Bold}[1]{\mathbf{#1}}34 \, y

计算\int {x\sin(x^2)}\int_0^1{\frac{x}{x^2+1}}

integral(x*sin(x^2), x) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}-\frac{1}{2} \, \cos\left(x^{2}\right)
\newcommand{\Bold}[1]{\mathbf{#1}}-\frac{1}{2} \, \cos\left(x^{2}\right)
integral(x/(x^2+1), x, 0, 1) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{2} \, \log\left(2\right)
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{2} \, \log\left(2\right)

\frac{1}{x^2-1}展开成部分分式:

f = 1/((1+x)*(x-1)) f.partial_fraction(x) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{2 \, {\left(x - 1\right)}} + \frac{-1}{2 \, {\left(x + 1\right)}}
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{1}{2 \, {\left(x - 1\right)}} + \frac{-1}{2 \, {\left(x + 1\right)}}
print f.partial_fraction(x) 
       
1/2/(x - 1) - 1/2/(x + 1)
1/2/(x - 1) - 1/2/(x + 1)

求解微分方程

可以用Sage研究常微分方程。求解方程x'+x-1=0

t = var('t') # 定义变量t x = function('x',t) # 定义x是该变量t的一个函数 DE = diff(x, t) + x - 1 desolve(DE, [x,t]) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}{\left(c + e^{t}\right)} e^{\left(-t\right)}
\newcommand{\Bold}[1]{\mathbf{#1}}{\left(c + e^{t}\right)} e^{\left(-t\right)}

这里用到了Sage的Maxima[Max]接口,因此输出结果可能与Sage的其它输出有些不同。在本例中,微分方程的通解为x(t)=e^-t(e^t+c)。

拉普拉斯变换

同样可以进行拉普拉斯变换;t^2e^t-sin(t)的拉普拉斯变换如下:

s = var("s") t = var("t") f = t^2*exp(t) - sin(t) f.laplace(t,s) 
       
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{2}{{\left(s - 1\right)}^{3}} + \frac{-1}{s^{2} + 1}
\newcommand{\Bold}[1]{\mathbf{#1}}\frac{2}{{\left(s - 1\right)}^{3}} + \frac{-1}{s^{2} + 1}