julia的语法不同于matlab,python,对于我这个maltab用户来说里面有诸多神奇的用法,大家都贴出来自己认为神奇或者很方便的用法吧
Generator Expressions
julia> sum(1/n^2 for n=1:1000)
1.6439345666815615
julia的语法不同于matlab,python,对于我这个maltab用户来说里面有诸多神奇的用法,大家都贴出来自己认为神奇或者很方便的用法吧
Generator Expressions
julia> sum(1/n^2 for n=1:1000)
1.6439345666815615
python里面也有生成器表达式,或者列表推导式:
# 生成器表达式
sum((1/(n**2) for n in range(1, 1000)))
# 列表推导式
sum([1/(n**2) for n in range(1, 1000)])
在python中,生成器对象类似于迭代器对象,具有惰性求值的特点,只在需要时生成新元素,具有更高的效率,内存空间占用非常少。
所以支持生成器表达式不止是 Julia 的特性。
@ v1.0
function add(x, y)
println("x is $x and y is $y")
x + y
end
add(5, 6)
add(5, 6)add(5, 6)
输出
julia> add(1,2)
x is 1 and y is 2
3
julia> add(5, 6)add(5, 6)
x is 5 and y is 6
x is 5 and y is 6
121
换一个直接返回值的
function f()
7
end
f()f()
julia> function f()
7
end
f (generic function with 1 method)
julia> f()f()
49
还可以结合着来
julia> add(5, 6)f()
x is 5 and y is 6
77
julia> add(f(), f())f()
x is 7 and y is 7
98
自动乘法?
julia> using BenchmarkTools
julia> @btime sum(1/n^2 for n=1:1000)
1.113 μs (0 allocations: 0 bytes)
1.6439345666815615
julia> @btime sum(n->1/n^2, 1:1000)
807.978 ns (0 allocations: 0 bytes)
1.6439345666815612
写成下面的形式,直接用函数的话更快。
感觉这个例子和这个有点像
julia> ᴴ(a) = a'; Base.:*(a, ::typeof(ᴴ)) = ᴴ(a)
julia> A = rand(2,2)
2×2 Array{Float64,2}:
0.910146 0.441134
0.793898 0.172196
julia> (A)ᴴ
2×2 LinearAlgebra.Adjoint{Float64,Array{Float64,2}}:
0.910146 0.793898
0.441134 0.172196
或者
julia> Base.adjoint(::typeof(sin)) = cos
julia> sin'(1)
0.5403023058681398
julia> cos(1)
0.5403023058681398
第一次看起来比较黑魔法。
这个应该是上面那个生成了一个数组,下面那个直接走的循环