Search code examples
juliaanglecallable

Error using Angle in Julia


I am simply trying to get the angle of a complex number. To test the angle function provided in Julia I first tried :

 angle(1+im)

But I get the following error message :

MethodError: objects of type Float64 are not callable

Stacktrace: [1] include_string(::String, ::String) at ./loading.jl:515

When I try to ask typeof(1+im) Julia answers

Complex{Int64}

I don't understand what is happening with the angle function. I tried with 1+1*im but I get the same answer.

Could anyone help please? I could also calculate the angle from coordinates but I'd like to understand Julia language as well.

Thank you


Solution

  • Sometimes it's possible to accidentally define a variable with the same name as a built-in function that you don't know about. For example, there's a function called angle(), but you can do this:

    julia> angle=1.5
    1.5
    
    julia> angle(1+1im)
    ERROR: MethodError: objects of type Float64 are not callable
    
    julia> typeof(angle)
    Float64
    

    Now you can't 'see' the function definition, because your variable is hiding it.

    To fix this, you can type:

    julia> angle=Base.angle
    angle (generic function with 3 methods)
    
    julia> angle(1+1im)
    0.7853981633974483
    

    A good question is, why doesn't Julia tell me I've just overwritten a basic function?

    Addendum

    And the answer (thanks to @Matt in a comment) is that if you use it, and then redefine it, you'll get a warning:

                  _
       _       _ _(_)_     |  A fresh approach to technical computing
      (_)     | (_) (_)    |  Documentation: https://docs.julialang.org
       _ _   _| |_  __ _   |  Type "?help" for help.
      | | | | | | |/ _` |  |
      | | |_| | | | (_| |  |  Version 0.6.0 (2017-06-19 13:05 UTC)
     _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release
    |__/                   |  x86_64-apple-darwin13.4.0
    
    julia> angle(1+2im)
    1.1071487177940904
    
    julia> angle=1.5
    WARNING: imported binding for angle overwritten in module Main
    1.5