1
学习序列的产品,从Python的传递到朱莉娅,我想转换的旧代码,我有,就是计算这个表达的序列的产品:朱莉娅:以量化的方式
我在Python中有两个版本的代码,一个使用for
循环实现,另一个使用广播。该for
循环的版本是:
import numpy as np
A = np.arange(1.,5.,1)
G = np.array([[1.,2.],[3.,4.]])
def calcF(G,A):
N = A.size
print A
print N
F = []
for l in range(N):
F.append(G/A[l])
print F[l]
for j in range(N):
if j != l:
F[l]*=((G - A[l])/(G + A[j]))*((A[l] - A[j])/(A[l] + A[j]))
return F
F= calcF(G,A)
print F
而且矢量版本我已经从我的问题here响应了解到,这个函数:
def calcF_vectorized(G,A):
# Get size of A
N = A.size
# Perform "(G - A[l])/(G + A[j]))" in a vectorized manner
p1 = (G - A[:,None,None,None])/(G + A[:,None,None])
# Perform "((A[l] - A[j])/(A[l] + A[j]))" in a vectorized manner
p2 = ((A[:,None] - A)/(A[:,None] + A))
# Elementwise multiplications between the previously calculated parts
p3 = p1*p2[...,None,None]
# Set the escaped portion "j != l" output as "G/A[l]"
p3[np.eye(N,dtype=bool)] = G/A[:,None,None]
Fout = p3.prod(1)
# If you need separate arrays just like in the question, split it
return np.array_split(Fout,N)
我试图天真地翻译了Python for
循环代码朱莉娅:
function JuliacalcF(G,A)
F = Array{Float64}[]
for l in eachindex(A)
push!(F,G/A[l])
println(A[i])
for j in eachindex(A)
if j!=l
F[l]*=((G - A[l])/(G + A[j]))*((A[l] - A[j])/(A[l] + A[j]))
end
end
end
#println(alpha)
return F
end
A = collect(1.0:1.0:5.0)
G = Vector{Float64}[[1.,2.],[3.,4.]]
println(JuliacalcF(G,A))
但是,有没有办法做到这一点很巧妙地作为转播numpy
g矢量化版本?
你确定你需要一个矢量化的版本吗?如果你对性能感兴趣(和_probably_ vectorizing),我会先推荐你[profile](http://docs.julialang.org/en/stable/stdlib/profile/)你的代码,并看看[performance提示](http://docs.julialang.org/en/stable/manual/performance-tips/) –