Dot Macro Broadcasting and complex values

Dear Julians,

I observed some inconsistent behavior with the @. dot macro which drove me mad in the last hours. Please see my code below.

using FFTW
fs = 16.0
dt = 1.0/fs
N = 1024
t = 0:dt:(N-1)*dt
y = zeros(Float64, N)
@. y = 0.4 * sin(2.0 * pi * 2.0 * t)

Sx = fft(y) # FFT-spectrum of signal x
Sxx_DBL = conj.(Sx) .* Sx # results 1
@. Sxx_DBL = conj(Sx) * Sx # results 2

Please compare the lines commented with results 1 and results 2. Both should lead to identical results with complex values i.e. with a real and an imaginary part. However, results 2 occasionally lead to real part values only. But only from time to time. BTW, while trying it out at the moment I even can not reproduce the wrong behavior. But it occured several times. So that I can’t trust the @. macro at the moment. Any Ideas ?

The @. has to go after the =, or else it’s also doing in-place assignment (.=). Maybe you’re seeing something related to that?

julia> Sxx_DBL1 = conj.(Sx) .* Sx;

julia> Sxx_DBL2 = @. conj(Sx) * Sx;

julia> Sxx_DBL1 == Sxx_DBL2
true

(v1.5)

You say you only saw a difference sometimes. Can you find initial values that produce it consistently, or do the ones you provided produce the effect occasionally?

2 Likes

I’m not sure what you’re obtaining. You’re effectively computing abs2.(Sx), so this should only have a real part. From result 1:

julia> Sxx_DBL = conj.(Sx) .* Sx;

julia> all(iszero, imag(Sxx_DBL))
true

Are you obtaining a Real array, as in elements that are real numbers and not complex with zero imaginary parts?

1 Like

The @. has to go after the = , or else it’s also doing in-place assignment ( .= ). Maybe you’re seeing something related to that?

I was not aware of that. Thanks.

You say you only saw a difference sometimes. Can you find initial values that produce it consistently, or do the ones you provided produce the effect occasionally?

I’ll further investigate or try to force that behavior and will report

Thanks fo the response !!

Are you obtaining a Real array, as in elements that are real numbers and not complex with zero imaginary parts?

That’s exactly the point. I observe both: Complex array with 0 imaginary parts AND a real Array with the real parts only. I’ll further investigate and report.