Julia教程2 REPL与变量

开始使用Julia

注意
目前网上的很多教程都是0.3版本,大家在学习的时候要区分一下,0.3版本的有些语法在1.0中已经不能使用

在Julia的REPL下,有多种模式:

  • help模式,按?进入help模式
  • shell模式,按;进入shell模式
  • package模式,按]进入package模式
  • backspace键返回正常Julia模式

也可以在REPL中运行一些简单的运算,或者定义函数等

image

在help模式下,可以查看各种帮助文档,就相当于执行@doc命令;

在package模式下,可以增加、删除各种库,相当于用Pkg这个模块来操作;
package模式下的add GR相当于Pkg.add("GR")
package模式下的rm GR相当于Pkg.rm("GR")

其他关于package的操作

Pkg.installed()  #查看已安装的库和它们的版本
Pkg.update()     #升级安装的库

我们在julia的目录下新建一个helloworld.jl的文件,里面内容为:

println("Hello World!")

在Windows中,shell模式下,执行julia helloworld.jl,即可运行该文件。

image

变量

可以参考知乎的文章《Python/Matlab/Julia基本语法比较》

像其他的动态语言一样,可以无需声明直接赋值

x = 10
x = "Hello world!"
x = 1.1
x = "这是Julia教程

变量名还可以是中文,当然不推荐这么做

测试 = 10
测试+1

还可以输入\+符号名称的方式来输入更多的Unicode数学字符,如\alpha后按tab键就会出现α的字符。
命名规范
跟其他编程语言的命名规范基本相同,如:

  • 变量名尽量小写
  • 类型和模块名首字母大写,单词间使用驼峰式分隔
  • 在几个单词不易区分时才以_分隔,一般不鼓励使用下划线_
  • 函数名和宏名使用小写字母,不使用下划线
  • 修改参数的函数结尾使用!,这样的函数被称为mutating functions或in-place functions

整型和浮点

整数类型

TypeSignedNumber of bitsSmallest valueLargest value
Int88-2^72^7-1
UInt8802^8-1
Int1616-2^152^15-1
UInt161602^16-1
Int3232-2^312^31-1
UInt323202^32-1
Int6464-2^632^63-1
UInt646402^64-1
Int128128-2^1282^127-1
UInt12812802^128-1
BoolN/A8false(0)true(1)
a = typoef(2)
>>Int64
typeof(a)
>>DataType
typeof(DataType)
>>DataType
b = supertype(a)
>>Signed
supertype(Signed)
>>Integer
supertype(Integer)
>>Real
supertype(Real)
>>Number
supertype(Number)
>>Any
supertype(Any)
>>Any
subtypes(Integer)
>>3-element Array{Any,1}:
 Bool    
 Signed  
 Unsigned
 sizeof(1)
 >>8
 sizeof(Int16(1))
 >>2

浮点数

TypePrecisionNumber of bits
Float16half16
Float32single32
Float64double64

在32位系统中,整数默认是Int32类型,浮点数默认是Float32类型;
在64位系统中,整数默认是Int64类型,浮点数默认是Float64类型。

x = 1
typeof(x)
>>Int64
a = tpyeof(1.1)
>>Float64
typeof(a)
>>DataType
typeof(DataType)
>>DataType
sizeof(Float64)
>>8
sizeof(Int128)
>>16
sizeof(Bool)
>>1
sizeof(Signed)
>>argument is an abstract type; size is indeterminate
    
    Stacktrace:
     [1] sizeof(::Type) at .\essentials.jl:405
     [2] top-level scope at In[15]:1

可以使用Sys.WORD_SIZE命令查看系统是32位还是64位,
也可以直接输入IntUInt看系统位数

JUlia中的很多语法和REPL的用法都跟matlab很像,比如上一次的结果用ans表示

julia> x = 1
1
julia> ans + 1
2

十六进制

由于Julia的整数中定义了Int和UInt两种大类型,其中Int用十进制表示,UInt类型用十六进制表示,当然我们也可以以0b开头表示二进制,以0o开头表示八进制

x = 10
UInt8(x)
>>0x0a
x = 0b1010
Int64(x)
>>10

二进制和十六进制也支持有符号数,直接在前面加-即可

-0xa
>>0xf6
bitstring(2)
>>"0000000000000000000000000000000000000000000000000000000000000010"
bitstring(-2)
>>"1111111111111111111111111111111111111111111111111111111111111110"

查看某种进制类型的最大最小值:

(typemin(Int32), typemax(Int32))
>>(-2147483648, 2147483647)
typemax(Int64)+1
>>-9223372036854775808

浮点数表示方法

1e-3
>>0.001
typeof(ans)
>>Float64
1f-3
>>0.001f0
typeof(ans)
>>Float32

浮点的0.0和-0.0在表示方式中也是有点分别的

0.0 = -0.0
>>true
bitstring(0.0)
>>"0000000000000000000000000000000000000000000000000000000000000000"
bitstring(-0.0)
>>"1000000000000000000000000000000000000000000000000000000000000000"

精度

eps(Float32)
>>1.1920929f-7
eps(Float64)
>>2.220446049250313e-16

数值越大,精度也就越低,也就是说,浮点数在0附近最稠密,随着数值越来越大,数值越来越稀疏,数值间的距离呈指数增长。

eps(1.0)
2.220446049250313e-16
eps(1000.)
1.1368683772161603e-13

舍入模型

1.1+0.1
>>1.2000000000000002

任意精度的运算

BigInt(typemax(Int64)) + 1
>>9223372036854775808
x=BigFloat(1.1+0.1)
>>1.20000000000000017763568394002504646778106689453125

BigFloat也是有默认的长度的,不过我们可以调节,但每次调节只能do模块里面的精度

setrounding(BigFloat, RoundUp) do
           BigFloat(1) + parse(BigFloat, "0.1")
       end
>>1.100000000000000000000000000000000000000000000000000000000000000000000000000003
setrounding(BigFloat, RoundDown) do
1.            BigFloat(1) + parse(BigFloat, "0.1")
       end
>>1.099999999999999999999999999999999999999999999999999999999999999999999999999986
setprecision(40) do
           BigFloat(1) + parse(BigFloat, "0.1")
       end
>>1.1000000000004

一个简单的递归函数,函数的具体用法将在后面讲到

function showTypeTree(T, level = 0)
    println("\t" ^ level, T)
    for t in subtypes(T)
        if t!= Any
            showTypeTree(t, level + 1)
        end
    end
end
>>showTypeTree (generic function with 2 methods)
showTypeTree(Real)
>>Real
	AbstractFloat
		BigFloat
		Float16
		Float32
		Float64
	AbstractIrrational
		Irrational
	Integer
		Bool
		Signed
			BigInt
			Int128
			Int16
			Int32
			Int64
			Int8
		Unsigned
			UInt128
			UInt16
			UInt32
			UInt64
			UInt8
	Rational

复数和分数

复数

x = 1 + 2im
(1 + 2im)*(2 - 3im)
>>8 + 1im
(1 + 2im)^2
>>-3 + 4im
2(1 - 1im)
>>2 - 2im

运算优先级

2/5im  #表示2/(5*im)
2/5im==-2/5*im

复数的其他运算

sqrt(2 + 3im)
cos(1 + 2im)
exp(1 + 2im)
abs(1 + 2im)
sqrt(-1)  #error
sqrt(-1 + 0im)
x = 1
y = 2
z1 = x + y*im
z2 = complex(x,y)
real(z1)
angle(1+2im)

分数

2//3
2//4
>>1//2
numerator(2//3) #分子
denominator(2//3) #分母
float(1//2)
isequal(float(a//b),a/b)

字符串

x = 'a' #用单引号表示字符
Int(x)
Char(ans)
## ASCII码对应
'\u21' # !
Int('\t')

str = "Hello World!"
str[1]  #Julia的下标从1开始
str[end-3:end]

又见蛋疼的编码

Julia 完整支持 Unicode 字符和字符串,Unicode码位可以使用\u\U来转义,在Julia中,非ASCII字符使用UTF-8编码,但UTF-8编码是一种变长的编码方式,也就是说不同字符的编码长度可能不同,这就导致在使用一些非常见字符时可能会碰到蛋疼的问题。

str = "\u2200 x \u2203 y"
>>"∀ x ∃ y"
str[1]
>>'∀': Unicode U+2200 (category Sm: Symbol, math)
str[2]
>>ERROR:...
str[3]
>>ERROR:...
str[4]
>>' ': ASCII/Unicode U+0020 (category Zs: Separator, space)

在UTF-8的编码中,’\u2200’即’∀’使用了三个字符,因此str[2]和str[3]都是无效的。str[4]为空格。
但可以这么使用:

str[1:4]

也可以使用firstindex()lastindex()来索引

for i = firstindex(str):lastindex(str)
    try
        println(s[i])
    catch
    
    end
end
>>∀
 
x
 
∃
 
y

当然,也可以像Python一样,直接将字符串当做遍历对象,而且不需要异常处理:

for i in s
    println(i)
end

字符串的其他操作

x = "Helllo"
y = "World"
string(x,",",y,"\n")
>>Hello,World\n
x * ',' * y
>>"Hello,World"
string("$x $y !")
>>"Hello World !"
n = 4
"nnnn has $n n"
>>"nnnn has 4 n"
"1/3 is about $(1/3)"
>>"1/3 is about 0.3333333333333333"
"$x,$y\n"
>>"Helllo,World\n"
"1 + 2 = $(1 + 2)"
>>"1 + 2 = 3"
v = [1,2,3]
"v: $v"
>>"v: [1, 2, 3]"
# 由于$是一个特殊字符,在当做文字使用时需转义
println("\$100")
>>$100
"abc" ^ 3
>>"abcabcabc"
lowercase("HELLO")
uppercase("hello")
replace("I want to learn Python", "Python" =>  "Julia")
replace("ABCD", 'A'=>'E')
startswith("julia is interesting", "julia")
>>true
startswith("  julia is interesting", "julia")
>>false
startswith(strip("  julia is interesting"), "julia")
>>true
s = split("one two three")
>>3-element Array{SubString{String},1}:
 "one"  
 "two"  
 "three"
join(s)
>>"onetwothree"
join(s, " ")
>>"one two three"

跨多行的字符串

"""
Hello,
world."""
>>"Hello,\nworld."

字符串的数学运算

“abcde" < "xyz"
>>true
"abcd" != "abcde"
>>true
"1 + 2 = 3" == "1 + 2 = $(1+2)"
>>true
findfirst(isequal('x'),"xilinx")
>>1
findnext(isequal('x'),"xilinx",1)
>>1
findnext(isequal('x'),"xilinx",2)
>>6
occursin("world", "Hello, world.")
>>true
repeat('a',10)
>>"aaaaaaaaaa"
x = "abcd..."
repeat(x,10)
>>"abcd...abcd...abcd...abcd...abcd...abcd...abcd...abcd...abcd...abcd..."
join(["abcd","efg","kmn","xyz"],","," and ")
>>"abcd,efg,kmn and xyz"
x = "abcdefgh"
firstindex(x)
>>1
lastindex(x)
>>8
length(x)
>>8
length(x,2,4)

有字符串的地方当然少不了正则表达式

r"^\s*(?:#|$)"
typeof(ans)
>>Regetx
occursin(r"^\s*(?:#|$)", "not a comment")
>>false
occursin(r"^\s*(?:#|$)", "# a comment")
>>true
m = match(r"abc","abcdefgh")
>>RegexMatch("abc")
m = match(r"[0-9]","aaaa1aaaa2aaaa3",1)
>>RegexMatch("1")
m = match(r"[0-9]","aaaa1aaaa2aaaa3",6)
>>RegexMatch("2")

Tuple

()表示,内容不可更改

x1 = (1,2,3,4)
x1[1] # 序号从1开始
length(x1)
x1[2:end]
x2 = (1, 2.4, 'a', "hello")
x3 = (a=1, b = 2)
x3.a
>>1

字典

Julia中也支持字典类型

dic = Dict("aa" => 1, "bb" => 2, "cc" => 3)
typeof(dic)
>>Dict{String,Int64}
dic.count
dic.keys
dic.vals
dic["aa"]

也可以把Array转成字典

ary = ["one" => 1, "two" => 2]
Dict(ary)

把Array中的Tuple转成字典

tpl = [("one", 1), ("two", 2)]
Dict(tpl)

把两个Array组合成Dict

vas = [1, 2, 3]
kes = ["one", "two", "three"]
Dict(zip(kes, vas))

新建一个空字典

d = Dict()
d["one"] = 1

在新建空字典时指定类型

d = Dict{String,Int64}()

字典遍历

d = Dict("one" => 1, "two" => 2, "three" => 3)
for (k,v) in d
    println("value is $k for key $v")
end

for v in values(d)
    println(v)
end

字典的其他用法

d = Dict("one" => 1, "two" => 2)
get(d, "three", -1)
get(d, "one", -1)
delete!(d, "one")

# 使用fieldnames查看该类型的fieldname
fieldnames(typeof(d))

Set

S = Set([1, 2, 3, 2])
S = Set(1:3:10)
2 in S
4 in S
issubset([1,4], S)  # [1,4] ⊆ S

A = Set([1, 2, 3, 4])
B = Set([2, 4, 6, 7])
# A 交 B
intersect(A,B)

# A 或 B
union(A, B)

# 注:不是Set也可以进行交/或操作,但返回不是Set
interset([1,2,3,4], [2,4,6,7])

微信公众号:Quant_Times

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值