Where is the syntax error in this Julia function - julia

I have the following code:
using Winston
function testConjecGeneral(n,numTrials)
rangeVec = 2.0
uppBound = zeros(length(rangeVec), 1)
count = 1
for alpha = rangeVec
uppBound(count) = n*renyi([0.25, 0.5, 0.25], alpha)
println("Upper bound: $(uppBound(count))")
count = count+1
end
end
When I try to load the code, using include("testConjecGeneral.jl") at the command prompt, I get ERROR: syntax: missing comma or ) in argument list
while loading /home/ganesh/UROP/YuryJulia/testConjecGeneral.jl, in expression starting on line 3
Can someone help me figure this out?

uppBound(count) = n*renyi([0.25, 0.5, 0.25], alpha)
doesn't look right to me. zeros returns an array and the right way to reference an array item is with square brackets. As written now it looks like it's trying call a function. Does changing that line to:
uppBound[count] = n*renyi([0.25, 0.5, 0.25], alpha)
fix the problem?

I don't think this is a syntax error, but rangeVec is not what you seem to think it is. You assign to rangeVec the Float64 value 2.0 and then you treat rangeVec like an Array, calling length(rangeVec) and looping over alpha = rangeVec. Do you mean for rangeVec to be an Array or a Float64?

Related

I am facing a challenge with julia range

I am new to Julia.
While trying out examples online, I got to the plot below:
using Plots
# 10 data points in 4 series
xs = range(0, 2π, length = 10)
data = [sin.(xs) cos.(xs) 2sin.(xs) 2cos.(xs)]
# We put labels in a row vector: applies to each series
labels = ["Apples" "Oranges" "Hats" "Shoes"]
# Marker shapes in a column vector: applies to data points
markershapes = [:circle, :star5]
# Marker colors in a matrix: applies to series and data points
markercolors = [
:green :orange :black :purple
:red :yellow :brown :white
]
plot(
xs,
data,
label = labels,
shape = markershapes,
color = markercolors,
markersize = 10
)
The Problem I am facing is at the beginning. Even if I try below alone on REPL
julia> xs = range(0, 2π, length = 10)
I receive the error below:
ERROR: MethodError: no method matching range(::Int64, ::Float64; length=10)
Closest candidates are:
range(::Any; length, stop, step) at range.jl:76
Stacktrace:
[1] top-level scope at none:0
Did I forget to include some Package?
Which version of Julia are you using? It sounds like you are using a version that is older than the tutorial you are reading. I can verify that range(0, 2π, length = 10) yields 0.0:0.6981317007977318:6.283185307179586 on Julia 1.5 and Julia 1.6, even without specifying stop
I guess I should have made more research before posting. it's an error in the original post I guess.
I should have used:
julia> xs = range(0, stop=2π, length = 10)
0.0:0.6981317007977318:6.283185307179586
No more errors!!
It's weird, I am following official tutorial... :((

how to correctly pass a value to an included function?

I have 2 julia files, alpha.jl and beta.jl.
in alpha.jl, there are 2 functions:
der that returns a derivative using Zygote,
derPlot that plots the function as well as the derivative:
function der(f, x)
y = f'(x)
return y
end
function derPlt(der,z)
plot(f, aspect_ratio=:equal, label="f(x)")
g(f,x₀) = (x -> f(x₀) + f'(x₀)*(x-x₀))
plot!(g(f,x), label="dy",color="magenta")
xlims!(-z,z)
ylims!(-z,z)
end
everything comes out fine when i call these 2 functions in beta.jl, after including the files:
include("alpha.jl")
f(x)=-x^2+2
x = -1.3
derPlt(der(f, x), 6)
However, if i directly enter in a value for the function, the plotted derivative line doesnt update; i.e, if i enter 2.0 instead of passing in some variable named x,
derPlt(der(f, 2.0), 6)
no change is reflected on the plot. New to Julia, trying to understand and fix it.
I think it's because in your derPlt function, you call
plot!(g(f,x),...)
on x instead of the z argument. The problem is then that you define a x = -1.3, the value of which is used inside of derPlt, regardless of what z argument you feed it.
Maybe replace that line with
plot!(g(f,z),...)
and you should be fine.
Seeing as this is a follow up to a question I answered previously I thought I'd have to respond: Benoit is broadly speaking correct, you are running into a scoping issue here, but a few more changes are in order.
Note that your function signature is derPlot(der, z) but then:
You never actually use the der argument in your function body; and
You construct your tangent line as g(f,x₀) = (x -> f(x₀) + f'(x₀)*(x-x₀)) - note that there's no z in there, only an x
Now where does that x come from? In the absence of any x argument being passed to your function, Julia will look for it in the global scope (outside your function). Here, you define x = -1.3, and when you then call derPlt, that's the x that will be used to construct your tangent, irrespective of the z argument you're passing.
Here's a cleaned up and working version:
using Plots, Zygote
function derPlt(f,z)
plot(f, label="f(x)", aspect_ratio = :equal,
xlims = (-5,5), ylims = (-5,5))
g(f,x₀) = (z -> f(x₀) + f'(x₀)*(z-x₀))
plot!(i -> g(f, z)(i), label="dy",color="magenta")
end
f(x)=-x^2+2
derPlt(f, -1.5)
I would encourage you to read the relevant manual section on Scope of Variables to ensure you get an understanding of what's happening in your code - good luck!

Julia's DifferentialEquations issue in converting solution to array

I solved a system of differential equations (van der Pol equations) using DifferentialEquations.
I would like to export the solution. To do this I used convert(Array,sol), however, the converted solution is not the same as the solution I get by sol.
See the code below for more explanation:
using DifferentialEquations
using Plots
function fun(du,u,p,t)
du[1] = u[2]
du[2] = 1000*(1-u[1]^2)*u[2]-u[1]
end
u0 = [2.0,0.0]
tspan = (0.0,3000.0)
prob = ODEProblem(fun,u0,tspan)
sol = solve(prob)
a = convert(Array,sol)#Here I tried to convert the solution to an array
plot(a[1,:])
plot(sol,vars = 1)
a = convert(Array,sol)
plot(a[1,:]) returns:
plot(sol,vars = 1) returns:
The converted solution is the same as what is contained in sol. The problem lies in the fact that the step size for the variable in the x axis (here it is time) is not uniform. So only plotting using plot(a[1,:]) is not enough. We must provide at what time the solution has the value it has. Using plot(sol.t,a[1,:]) plot the right answer.

Plotting a function in scilab

can you help me, I 'm trying to plot the function y=1/x in scilab,
the graph that throws me is incorrect
x = [1:1:10]';
y = 1./x;
plot(x,y)
and throws me these results
y=
0.0025974
0.0051948
0.0077922
0.0103896
0.0129870
0.0155844
0.0181818
0.0207792
0.0233766
0.0259740
and this result is wrong , as would be the code ,
Thanks for the help :)
Write
y = 1 ./ x;
instead of
y = 1./x;
From the documentation (emphasis is mine):
a ./ b is the matrix with entries a(i,j)/ b(i,j). If b is scalar (1x1 matrix) this operation is the same as a./b*ones(a). (Same convention if a is a scalar).
Remark that 123./b is interpreted as (123.)/b. In this cases dot is part of the number not of the operator.

Correct usage of Interpolations.jl outside the domain

I'm porting a Matlab code into julia and so far i'm having amazing results:
A code that in Matlab runs in more than 5 hours, julia does it in a little more than 8 minutes! however i have a problem...
In matlab i have:
for xx=1:xlong
for yy = 1:ylong
U_alturas(xx,yy,:) = interp1(squeeze(NivelAltura_int(xx,yy,:)),squeeze(U(xx,yy,:)), interpolar_a);
V_alturas(xx,yy,:) = interp1(squeeze(NivelAltura_int(xx,yy,:)),squeeze(V(xx,yy,:)), interpolar_a);
end
end
that produces NaNs whenever a point in interpolar_a is outside the range in NivelAltura_int.
In Julia i'm trying to do the same with:
for xx in 1:xlong
for yy in 1:ylong
AltInterp = interpolate((Znw_r,),A_s_c_r,Gridded(Linear()));
NivelAltura_int[xx,yy,1:end] = AltInterp[Znu[1:end]]
Uinterp = interpolate((squeeze(NivelAltura_int[xx,yy,1:end],(1,2)),),squeeze(U[xx,yy,1:end],(1,2)),Gridded(Linear()));
Vinterp = interpolate((squeeze(NivelAltura_int[xx,yy,1:end],(1,2)),),squeeze(V[xx,yy,1:end],(1,2)),Gridded(Linear()));
U_alturas[xx,yy,1:end] = Uinterp[Alturas[1:end]];
V_alturas[xx,yy,1:end] = Vinterp[Alturas[1:end]];
end
end
using the package Interpolations.jl. Whenever the point is outside the domain, this package extrapolates, which is incorrect for my purposes.
I can add a few lines of code that check and substitutes the values outside the domain with NaNs, but i believe it would add some time to the computation and is not very elegant.
In the documentation of the package, it mentions a kind of object like this:
Uextrap = extrapolate(Uinterp,NaN)
To control the behavior outside the domain, but i haven't find how to use it, i've tried adding it under Uinterp, i've tried evaluating it but it, naturally, won't work that way.
Could you help me on this one?
Thanks!
It looks like you may be running into two issues here. First, there's been some recent work on gridded extrapolations (#101) that may not be in the tagged version yet. If you're willing to live on the edge, you can Pkg.checkout("Interpolations") to use the development version (Pkg.free("Interpolations") will put you back on the stable version again).
Secondly, it looks like there's a still a missing method for vector-valued gridded extrapolations (issue #24):
julia> using Interpolations
itp = interpolate((collect(1:10),), collect(.1:.1:1.), Gridded(Linear()))
etp = extrapolate(itp, NaN);
julia> etp[.5:1:10.5]
ERROR: BoundsError: # ...
in throw_boundserror at abstractarray.jl:156
in getindex at abstractarray.jl:488
As you can see, it's trying to use the generic definitions for all abstract arrays, which will of course throw bounds errors. Interpolations just needs to add its own definition.
In the mean time, you can use a comprehension with scalar indexing:
julia> [etp[x] for x=.5:1:10.5]
11-element Array{Any,1}:
NaN
0.15
0.25
0.35
0.45
0.55
0.65
0.75
0.85
0.95
NaN
The following sample (refer) shows how extrapolate works:
Preparation:
using Interpolations
f(x) = sin((x-3)*2pi/9 - 1)
xmax = 10
A = Float64[f(x) for x in 1:xmax] # domain .EQ. 1:10
itpg = interpolate(A, BSpline(Linear()), OnGrid())
The itpg object extrapolates outside points conforming its interpolation type:
itpg[2] # inside => -0.99190379965505
itpg[-2] # outside => 0.2628561875219271
Now we use extrapolat object to control extrapolation behavior:
etpg = extrapolate(itpg, NaN);
etpg[2]==itpg[2] # same result when point is inside => true
isnan(etpg[-2]) # NaN when the point is outside => true
So an extrapolate object does interpolation conforming its parent while extrapolates in a custom manner.

Resources