How to migrate old julia code that called a function with a range

I’d used some really old versions of julia circa 2015, and recently installed 1.4.2 to play around with the current version.

I used to be able to compute arrays of function call values (at least for some types of functions) using ranges (in a way that I seem to recall was matlab like). Here is an example:

   theta = linrange( 0, 1 * pi, 500 ) ;
   ct = pi * cos(theta) ;

With julia-1.4.2 I have to update the linrange to use range or LinRange, but even after doing so, I’m not able to call cos() using a range anymore:

julia> theta = range( 0, stop=pi, length=500)
0.0:0.006295776860901389:3.141592653589793

julia> cos(theta)
ERROR: MethodError: no method matching cos(::StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}})
Closest candidates are:
  cos(::BigFloat) at mpfr.jl:683
  cos(::Missing) at math.jl:1056
  cos(::Complex{Float16}) at math.jl:1005
  ...
Stacktrace:
 [1] top-level scope at none:0

Is there a new paradigm to thread a function over a range in this more modern Julia version?

You should broadcast theta:

cos.(theta)

https://docs.julialang.org/en/v1/manual/arrays/#Broadcasting-1

1 Like

You might specifically want ct = cospi.(theta) the trig functions with pi in the end of their name are a little more accurate than multiplying by pi since multiplying by an irrational adds some error.
Edit: this is only if you wanted cos.(pi*x) not pi*cos.(x)

2 Likes

Thanks Lucus. That explicit syntax is nice. I’ll give it a try.