Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using linspace in Julia 0.7

Tags:

julia

I am confused about using linspace in Julia 0.7. Here is the what I entered in the REPL and the result:

julia> a = linspace(0.1,1.1,6)
┌ Warning: `linspace(start, stop, length::Integer)` is deprecated, use `range(start, stop=stop, length=length)` instead.
│   caller = top-level scope
└ @ Core :0
0.1:0.2:1.1

My question is about the deprecated warning and the suggested use of range. The range statement doesn't do the same thing as the linspace command.

If you enter the a = linspace(0.1,1.1,6) and collect(a), you get the following:

julia> collect(a)
6-element Array{Float64,1}:
 0.1
 0.3
 0.5
 0.7
 0.9
 1.1

If you enter b = range(0.1,1.1,6) and collect(b), you get:

julia> collect(b)
6-element Array{Float64,1}:
 0.1
 1.2
 2.3
 3.4
 4.5
 5.6

This is obviously not the same.

Why is linspace deprecated (perhaps a different question) and a non-equivalent range command suggested?

My actual question is: Is it safe to keep using linspace for the desired results it provides, and, if not, what should I be using instead?

like image 857
djWestTexas Avatar asked Jun 21 '18 18:06

djWestTexas


2 Answers

You should use LinRange, as documented here.

A range with len linearly spaced elements between its start and stop. The size of the spacing is controlled by len, which must be an Int.

julia> LinRange(1.5, 5.5, 9)
9-element LinRange{Float64}:
 1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0,5.5

Edit 2021: As of version 1.7 you can use the range function for this:

jl> range(1.5, 5.5, 9)
1.5:0.5:5.5

For version 1.6 you have to write: range(1.5, 5.5, length=9).

like image 119
DNF Avatar answered Nov 13 '22 08:11

DNF


Following the deprecations, it is now:

julia> range(0.1, stop = 1.1, length = 6) |> collect
6-element Array{Float64,1}:
 0.1
 0.3
 0.5
 0.7
 0.9
 1.1

In your example, the second argument is a step, not the stop, notice this method is also deprecated, you have to use keyword arguments now:

julia> @which range(0.1, 1.1, 6)
range(start, step, length) in Base at deprecated.jl:53
like image 29
HarmonicaMuse Avatar answered Nov 13 '22 09:11

HarmonicaMuse