赋值、等式和算术¶
除了一些小的例外,Sage使用Python编程语言,所以关于Python的大多数介绍性书籍都将帮助您学习Sage。
Sage使用 =
分配。它使用 ==
, <=
, >=
, <
和 >
作为比较:
sage: a = 5
sage: a
5
sage: 2 == 2
True
sage: 2 == 3
False
sage: 2 < 3
True
sage: a == 5
True
Sage提供所有基本的数学运算:
sage: 2**3 # ** means exponent
8
sage: 2^3 # ^ is a synonym for ** (unlike in Python)
8
sage: 10 % 3 # for integer arguments, % means mod, i.e., remainder
1
sage: 10/4
5/2
sage: 10//4 # for integer arguments, // returns the integer quotient
2
sage: 4 * (10 // 4) + 10 % 4 == 10
True
sage: 3^2*4 + 2%5
38
像这样的表达式的计算 3^2*4 + 2%5
取决于应用操作的顺序;这在中的“运算符优先表”中指定 算术二元运算符优先级 .
Sage还提供了许多常见的数学函数;下面是几个示例:
sage: sqrt(3.4)
1.84390889145858
sage: sin(5.135)
-0.912021158525540
sage: sin(pi/3)
1/2*sqrt(3)
正如最后一个例子所示,一些数学表达式返回“精确”值,而不是数值近似值。若要获得数值近似值,请使用函数 N
或者方法 n
(它们都有一个较长的名字, numerical_approx
以及功能 N
是一样的 n
)). 它们采用可选参数 prec
,这是请求的精度位数,以及 digits
,这是所请求的精度小数位数;默认值为53位精度。
sage: exp(2)
e^2
sage: n(exp(2))
7.38905609893065
sage: sqrt(pi).numerical_approx()
1.77245385090552
sage: sin(10).n(digits=5)
-0.54402
sage: N(sin(10),digits=10)
-0.5440211109
sage: numerical_approx(pi, prec=200)
3.1415926535897932384626433832795028841971693993751058209749
Python是动态类型化的,因此每个变量引用的值都有一个与之关联的类型,但是给定的变量可以保存给定范围内任何Python类型的值:
sage: a = 5 # a is an integer
sage: type(a)
<type 'sage.rings.integer.Integer'>
sage: a = 5/3 # now a is a rational number
sage: type(a)
<type 'sage.rings.rational.Rational'>
sage: a = 'hello' # now a is a string
sage: type(a)
<... 'str'>
C编程语言是静态类型的,与之大不相同;声明为保存int的变量只能在其作用域内保存int。