分配、等式和算术¶
除了一些小的例外,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)
<class 'sage.rings.integer.Integer'>
sage: a = 5/3 # now a is a rational number
sage: type(a)
<class 'sage.rings.rational.Rational'>
sage: a = 'hello' # now a is a string
sage: type(a)
<... 'str'>
静态类型的C编程语言则大不相同;声明为保存int的变量只能在其作用域中保存int。