数据类型

Sage中的每一个对象都有良好定义的类型。Python有广泛的基本内置类型,Sage库又添加了很多。Python内置的类型包括字符串,列表,元组,整数和实数等,如下:

  1. sage: s = "sage"; type(s)
  2. <... 'str'>
  3. sage: s = 'sage'; type(s) # 单引号和双引号都可以使用
  4. <... 'str'>
  5. sage: s =[1,2,3,4]; type(s)
  6. <... 'list'>
  7. sage: s = (1,2,3,4); type(s)
  8. <... 'tuple'>
  9. sage: s = int(2006); type(s)
  10. <... 'int'>
  11. sage: s = float(2006); type(s)
  12. <... 'float'>

Sage增加了很多其他类型,如,向量空间:

  1. sage: V = VectorSpace(QQ, 1000000); V
  2. Vector space of dimension 1000000 over Rational Field
  3. sage: type(V)
  4. <class 'sage.modules.free_module.FreeModule_ambient_field_with_category'>

只有特定的函数才能在作用在V上。其他数学软件中, 可能会用”函数”形式foo(V,...)。 在Sage中,特定的函数附加于V的类型(或类)上,并使用类似Java或C++的面向对象的语法,即,V.foo(...)。这可以使全局的命名空间保持整洁,而不被成千上万的函数搞乱。而且不同作用的函数都可以叫foo,还不用做参数的类型检查(或case语句)来决定要调用哪一个。如果你重用了一个函数的名字,那个函数还是可用的(如,你把什么东西命名为zeta, 然后又想计算0.5的Riemann-Zeta函数值,你还是可以输入s=.5; s.zeta())。

  1. sage: zeta = -1
  2. sage: s=.5; s.zeta()
  3. -1.46035450880959

通常情况下,常用的函数调用方式也是支持的,这样要方便些,而且数学表达式用面向对象的方式调用看着更不习惯。这有几个例子。

  1. sage: n = 2; n.sqrt()
  2. sqrt(2)
  3. sage: sqrt(2)
  4. sqrt(2)
  5. sage: V = VectorSpace(QQ,2)
  6. sage: V.basis()
  7. [
  8. (1, 0),
  9. (0, 1)
  10. ]
  11. sage: basis(V)
  12. [
  13. (1, 0),
  14. (0, 1)
  15. ]
  16. sage: M = MatrixSpace(GF(7), 2); M
  17. Full MatrixSpace of 2 by 2 dense matrices over Finite Field of size 7
  18. sage: A = M([1,2,3,4]); A
  19. [1 2]
  20. [3 4]
  21. sage: A.charpoly('x')
  22. x^2 + 2*x + 5
  23. sage: charpoly(A, 'x')
  24. x^2 + 2*x + 5

要列出$A$的所有成员函数,可以使用tab补全功能。先输入A., 再按[tab], 正如反向查找和Tab补全中介绍的。