How to define "complex Float64" variable in Julia?

Viewed 341

I have a module, say, called Constants,

module Constants
const zero = 0.0 :: Float64
const czero = 0.0 + 0.0im :: Complex
end

I know like I can define like zero as Float64. But How do I define a "Complex" and "Float64" variable such as czero? Currently I use Complex, but I want to be more specific. If I use ComplexF64

const czero = 0.0 + 0.0im :: ComplexF64

it gives me an error,

ERROR: LoadError: TypeError: in typeassert, expected Complex{Float64}, got a value of type Complex{Bool}

So what concrete type of Complex should I use? I give each variable a concrete type is because I heard that if the code looks like Fortran it can run like Fortran, because I define the type first so Julia do not have to convert the type which can be very slow.

2 Answers

This question is not quite clear, but perhpas what you need is zero:

julia> zero(ComplexF64)
0.0 + 0.0im

julia> dump(zero(ComplexF64))
ComplexF64
  re: Float64 0.0
  im: Float64 0.0

Other options include using the constructor such as ComplexF64(0.0) or ComplexF64(0.0,0.0) or using the complex(0.0) function. These are all type stable.

  ::

  With the ::-operator type annotations are attached to expressions and variables in programs. See the manual section on Type Declarations.

  Outside of declarations :: is used to assert that expressions and variables in programs have a given type.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> (1+2)::AbstractFloat
  ERROR: TypeError: typeassert: expected AbstractFloat, got a value of type Int64
  
  julia> (1+2)::Int
  3

With this in mind, obviously julia considers the declaration invalid because of operator precedence, so just put parentheses if you want to do the declaration this way

const czero = (0.0 + 0.0im) ::ComplexF64

I also second the opinion above: if you're just trying to declare zeros then what you need is zero

Related