I am porting some Python code into Julia (v1.3.1), and I have run into an issue with trying to reproduce the code into as easily readable code in Julia.
In Python (using numpy
), we have created a 101-element logarithmically spaced sequence from 0.001 to 1000:
>>> X = numpy.logspace( -3, 3, 101 )
array([1.00000000e-03, 1.14815362e-03, 1.31825674e-03, ..., 1.00000000e+03])
Implementing this in Julia with PyCall
would of course work like this:
julia> using PyCall
julia> numpy = pyimport("numpy")
julia> X_python = numpy.logspace( -3, 3, 101 )
101-element Array{Float64,1}:
0.001
0.0011481536214968829
0.0013182567385564075
⋮
1000.0
But I want to implement this in pure Julia for my current project. Not finding the same function from the Julia documentation, after some searching I came across an older documentation entry for logspace
here. I then came across this Github pull request for deprecating logspace
into its definition, so currently it seems that this is the way to create the logarithmically spaced sequence:
julia> X_julia = 10 .^ range( -3, 3, length = 101 )
101-element Array{Float64,1}:
0.001
0.0011481536214968829
0.0013182567385564075
⋮
1000.0
julia> LinRange(1e-3, 1e3, 101)
101-element LinRange{Float64}:
0.001,10.001,20.001,…,1000.0
Since there currently exists a simple and easy-to-read function, LinRange
, for creating linear sequences (as seen above), does there exist a similar function, something like LogRange
, for logarithmic sequences?
I am going for simplicity and improved readability in this project, so while broadcasting a range
into the exponent of 10 works from the mathematical point of view, something like LogRange(1e-3, 1e3, 101)
would be easier for a beginner or part-time programmer to understand.
EDIT: When the limits of the sequence are integer exponents of 10, the code is fairly clear, but when the limits are floats, the difference in readability between LogRange()
and 10 .^ ()
becomes more apparent:
julia> 10 .^ range( log10(1.56e-2), log10(3.62e4), length = 101 )
julia> LogRange( 1.56e-2, 3.62e4, 101 )
Can't you just define your own function logrange
, like this:
logrange(x1, x2, n) = (10^y for y in range(log10(x1), log10(x2), length=n))
?
This returns a generator, so it will not allocate an array, and should be easy to understand and use for other users.
You can just use range
For Log-spaced values ∈ [1.0e-10, 1.0e10]:
10 .^ range(-10, stop=10, length=101)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With