Julia: numbers and operators

355 阅读3分钟

Julia的数字和运算符

Integers and Floating-point Numbers

Julia提供了非常多的数字的原始类型(primitive numeric types)

  • 整数:Int8UInt8Int16UInt16Int32UInt32Int64UInt64Int128UInt128Bool
  • 浮点数:Float16Float32Float64

这些数字类型在32位和64位机器上都可以使用。默认的数字类型是机器的支持位数。

# 32-bit system:
julia> typeof(1)
Int32
# 64-bit system:
julia> typeof(1)
Int64

Julia也定义了IntUInt类型:

# 64-bit system:
julia> Int
Int64

Julia的整数可能出现上溢:

julia> x = typemax(Int64)
9223372036854775807
julia> x + 1
-9223372036854775808
julia> x + 1 == typemin(Int64)
true

为了防止上溢,可以使用大整数类型

julia> 10^19
-8446744073709551616
julia> big(10)^19
10000000000000000000
julia> BigInt(typemax(Int64)) + 1
9223372036854775808
julia> big"123456789012345678901234567890" + 1
123456789012345678901234567891
julia> parse(BigInt, "123456789012345678901234567890") + 1
123456789012345678901234567891

类似于MATLAB,Julia使用变量eps来表示最小能表示的浮点数:

julia> eps(Float32)
1.1920929f-7
julia> eps(Float64)
2.220446049250313e-16
julia> eps() # same as eps(Float64)
2.220446049250313e-16

Julia提供了函数nextfloatprevfloat返回下一个/上一个可表示的浮点数:

julia> x = 1.25f0
1.25f0
julia> nextfloat(x)
1.2500001f0
julia> prevfloat(x)
1.2499999f0

Numeric Literal Coefficients

Julia为了更加有数学味道,把MATLAB必须要在数和字母相乘时加*号给省略了。

julia> x = 3
3
julia> 2x^2 - 3x + 1  # 2 * (x ^ 2) - 3 * x + 1
10
julia> 2^2x  # 2 ^ (2 * x)
64
julia> (x-1)x
6
julia> x(x+1)
ERROR: MethodError: objects of type Int64 are not callable

注意在Julia语言中()也是用来调用方法的。为了消除歧义,0x1解释为十进制整数1而不是0乘以x1

Arithmetic Operators

对于数的运算,我们有如下运算符:

ExpressionNameDescription
+xunary plusthe identity operation
-xunary minusmaps values to their additive inverses
x + ybinary plusperforms addition
x - ybinary minusperforms subtraction
x * ytimesperforms multiplication
x / ydivideperforms division
x ÷ yinteger dividex / y, truncated to an integer
x \ yinverse divideequivalent to y / x
x ^ ypowerraises x to the yth power
x % yremainderequivalent to rem(x,y)

对于Bool类型,我们有!符号取反。

Bitwise Operators

对整数,我们也可以使用位运算:

ExpressionName
~xbitwise not
x & ybitwise and
xybitwise or
x ⊻ ybitwise xor (exclusive or)
x >>> ylogical shift right
x >> yarithmetic shift right
x << ylogical/arithmetic shift lef

Updating operators

大多数运算都可以使用更新运算符。

+= -= *= /= \= ÷= %= ^= &= |= ⊻= >>>= >>= <<=

Numeric Comparisons

Julia的以下比较运算符可以用于原始类型的比较:

OperatorName
==equality
!=, ≠inequality
<less than
<=, ≤less than or equal to
>greater than
>=, ≥greater than or equal to

注意NaN是一个特殊的数据类型,Julia有isequal函数来对某些特殊类型进行比较:

julia> NaN == NaN
false
julia> NaN != NaN
true
julia> NaN < NaN
false
julia> NaN > NaN
false
julia> [1 NaN] == [1 NaN]
false
julia> isequal(NaN, NaN)
true

Julia支持链式比较。如1 < 2 < 3

Numerical Conversions

Julia提供了两种方式来显式转换类型,T(x)convert(T,x),需要注意的是类型转换必须合法(即不出现上溢或者下溢)

关于复数和有理数,虽然Julia也有支持,但是一般用的不多,这里不再介绍。