Plotting a complex function

Dear All,
I am trying to put this function

using Plots
function test(t,t0,E,Ω)
    if t<t0
        E0=E*t0
        test=1im*E0/Ω *(1-exp.(1im*Ω*t))
        println("t is less than t0")
    else
        test=0
        println("t is grater than t0")
    end
end
plot(t->test(t,2,100,1), xlims=(0,10), label="test(t)";)


in a program but it shows me an error “MethodError: no method matching Float64(::Nothing)” while plotting.
However, if I use without 1im, it works well, e.g.

using Plots
function test(t,t0,E,Ω)
    if t<t0
        E0=E*t0
        test=E0/Ω *(1-exp.(Ω*t))
    else
        test=0
    end
end
plot(t->test(t,2,100,1), xlims=(0,10), label="test(t)";)

Please let me know how can I plot a complex function?

  1. Your first test function returns nothing. You should return a value. The second test function works because you don’t have the println statement in there, and you’re exploiting the fact that a function without an explicit return returns the result of the last statement. Still, you should have a return

  2. If I understand correctly, you have a function ℝ→ℂ. Plotting such a function doesn’t make sense. You can plot the real part, or the imaginary value, or the absolute value (or abs2). In general, you can only plot a function with a real output value. If your function was ℂ→ℝ, you could have a 3D plot.

  3. Some minor points:

    • Remove the print statements. You don’t want to print something every time the function evaluates
    • Consider making your function type stable. Don’t return 0, return zero(1im) so that it always returns a ComplexF64 independent of the value of t.
    • plot can do some automatic guessing for the values of t to plug in, but it’s better to give it the values over which you want to plot explicitly: plot(tvals, abs2.(test.(tvals)), …)
1 Like

@goerz: The blackboard bold real and complex symbols are neat! Do you have a macro to type the Unicode characters in Markdown? The only way I could figure to reproduce them was to copy-paste them:

julia> '\u2102'
'ℂ': Unicode U+2102 (category Lu: Letter, uppercase)

julia> '\u211d'
'ℝ': Unicode U+211D (category Lu: Letter, uppercase)

@goerz Perfect! Thanks.

Yes: The "U.S. International - Scientific" Keyboard Layout - Michael Goerz :blush:

2 Likes

neat!