Is there a Kronecker delta in Julia? - julia

If I have some declared some Points in Julia (p_1,...,p_n). Is there some function or algorithm for kronecker delta (f_i(p_j)=1 if i=j and f_i(p_j)=0 if i != j)
It would be very helpful.
Thank you so much.

If you want a kronecker delta function you can use the ==(x,y) function (as indicated by #mbauman in the comments).
julia> δ(x,y) = ==(x,y)
δ (generic function with 1 method)
julia> δ(1,1)
true
julia> δ(1,2)
false
Note that this returns true or false instead of 1 and 0 but the former are essentially equal to the latter and will behave in the same way, for example ==(1,1) * 2 will give 2. In fact, true isa Integer in Julia.
Another option might be to use I the (lazy) identity matrix built into Julia (LinearAlgebra that is):
julia> using LinearAlgebra
julia> I[1,1]
true
julia> I[1,2]
false

For an arbitrary number of arguments, you can do:
δ(x, y) = ==(x, y)
function δ(x, y, z...)
!δ(x, y) && return false
for i in z
!δ(x, i) && return false
end
return true
end
or if you make the convention that δ(x) := true:
δ(x, y) = ==(x, y)
function δ(z...)
for i in z
!δ(z[1], i) && return false
end
return true
end

Related

Recursion function to calculate factorial not working properly for larger numbers

I am taking a course in data-structures and trying to replicate the same in Julia.
I am using the below code in Julia -
function factorial(n)
if n <= 1
return 1
else
return n*factorial(n-1)
end
end
It is working fine with number less than or equal to 20, but for 21 and greater I am getting negative value. Same logic is working fine in Python, below is the code -
def factorial(n):
assert n >= 0 and int(n) == n, 'The number must be positive integer only'
if n <= 1:
return 1
else:
return n*factorial(n-1)
can you pleas help me understand what might be the problem?
As 张实唯 mentioned in the comments, you could pass in a BigInt as an input to calculate larger numbers.
To keep your code type stable, return one(n) instead of 1. This will make sure that whatever type was sent as input will be returned, keeping your code type stable.
julia> function factorial(n)
if n <= 1
return one(n)
else
return factorial(n - 1) * n
end
end
factorial (generic function with 1 method)
Outputs
julia> typeof(factorial(10))
Int64
julia> typeof(factorial(BigInt(10)))
BigInt
julia> typeof(factorial(big"100"))
BigInt
julia> factorial(big"100")
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Alternative one-liner
You could also write the above function as a line-liner, using Julia's ternary operator.
factorial(n) = n <= 1 ? one(n) : factorial(n-1) * n
As explained here:
In Julia, exceeding the maximum representable value of a given type results in a wraparound behavior
And the range for Int64 type (used by default on 64-bit machines to store integers) is:
julia> typemin(Int64)
-9223372036854775808
julia> typemax(Int64)
9223372036854775807
Instead use BigInt that implements arbitrary precision integers. You can convert any integer into BigInt using the big function. The downside of this approach is that the function will be slower:
function factorial(n)
if n <= 1
return big(1)
else
return big(n) * factorial(n-1)
end
end
And now you have:
julia> factorial(21)
51090942171709440000
julia> factorial(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
EDIT
The example showing that the code of OP is not type stable:
julia> using Test
julia> function factorial(n)
if n <= 1
return 1
else
return n*factorial(n-1)
end
end
factorial (generic function with 1 method)
julia> #inferred factorial(big"21")
ERROR: return type BigInt does not match inferred return type Union{Int64, BigInt}

Using ForwardDiff.jl for a function of many variables and parameters Julia

The github repo for ForwardDiff.jl has some examples. I am trying to extend the example to take in addition to a vector of variables, a parameter. I cannot get it to work.
This is the example (it is short so I will show it rather than linking)
using ForwardDiff
x = rand(5)
f(x::Vector) = sum(sin, x) .+ prod(tan, x) * sum(sqrt, x);
g = x -> ForwardDiff.gradient(f, x);
g(x) # this outputs the gradient.
I want to modify this since I use functions with multiple parameters as well as variables. As a simple modification I have tried adding a single parameter.
f(x::Vector, y) = (sum(sin, x) .+ prod(tan, x) * sum(sqrt, x)) * y;
I have tried the following to no avail:
fp = x -> ForwardDiff.gradient(f, x);
fp = x -> ForwardDiff.gradient(f, x, y);
y = 1
println("test grad: ", fp(x, y))
I get the following error message:
ERROR: LoadError: MethodError: no method matching (::var"#73#74")(::Array{Float64,1}, ::Int64)
A similar question was not answered in 2017. A comment led me to here and it seems the function can only accept one input?
The target function must be unary (i.e., only accept a single argument). ForwardDiff.jacobian is an exception to this rule.
Has this changed? It seems very limited to only be able to differentiate unary functions.
A possible workaround would be to concatenate the list of variables and parameters and then just slice the returned gradient to not include the gradients with respect to the parameters, but this seems silly.
I personally think it makes sense to have this unary-only syntax for ForwardDiff. In your case, you could just pack/unpack x and y into a single vector (nominally x2 below):
julia> using ForwardDiff
julia> x = rand(5)
5-element Array{Float64,1}:
0.4304735670747184
0.3939269364431113
0.7912705403776603
0.8942024934250143
0.5724373306715196
julia> f(x::Vector, y) = (sum(sin, x) .+ prod(tan, x) * sum(sqrt, x)) * y;
julia> y = 1
1
julia> f(x2::Vector) = f(x2[1:end-1], x2[end]) % unpacking in f call
f (generic function with 2 methods)
julia> fp = x -> ForwardDiff.gradient(f, x);
julia> println("test grad: ", fp([x; y])) % packing in fp call
test grad: [2.6105844240785796, 2.741442601659502, 1.9913192377198885, 1.9382805843854594, 2.26202717745402, 3.434350946190029]
But my preference would be to explicitly name the partial derivatives differently:
julia> ∂f∂x(x,y) = ForwardDiff.gradient(x -> f(x,y), x)
∂f∂x (generic function with 1 method)
julia> ∂f∂y(x,y) = ForwardDiff.derivative(y -> f(x,y), y)
∂f∂y (generic function with 1 method)
julia> ∂f∂x(x, y)
5-element Array{Float64,1}:
2.6105844240785796
2.741442601659502
1.9913192377198885
1.9382805843854594
2.26202717745402
julia> ∂f∂y(x, y)
3.434350946190029
Here's a quick attempt at a function which takes multiple arguments, the same signature as Zygote.gradient:
julia> using ForwardDiff, Zygote
julia> multigrad(f, xs...) = ntuple(length(xs)) do i
g(y) = f(ntuple(j -> j==i ? y : xs[j], length(xs))...)
xs[i] isa AbstractArray ? ForwardDiff.gradient(g, xs[i]) :
xs[i] isa Number ? ForwardDiff.derivative(g, xs[i]) : nothing
end;
julia> f1(x,y,z) = sum(x.^2)/y;
julia> multigrad(f1, [1,2,3], 4)
([0.5, 1.0, 1.5], -0.875)
julia> Zygote.gradient(f1, [1,2,3], 4)
([0.5, 1.0, 1.5], -0.875)
For a function with several scalar arguments, this evaluates each derivative separately, and perhaps it would be more efficient to use one evaluation with some Dual(x, (dx, dy, dz)). With large-enough array arguments, ForwardDiff.gradient will already perform multiple evaluations, each with some number of perturbations (the chunk size, which you can control).

generating expressions and then checking them in Julia

My goal is to be able to generate a list of expressions, p.g., check that a number is in some interval, and then evaluate it.
I was able to do it in the following way.
First, a function genExpr that creates such an Expr:
function genExpr(a::Real, b::Real)::Expr
quote
x < $(a + b) && x > $(a - b)
end
end
Create two expressions:
e1 = genExpr(0,3)
e2 = genExpr(8,2)
Now, my problem is how to pass these expressions to a function along with a number x. Then, this function, checks if such a number satisfies both conditions. I was able to achieve it with the following function:
function applyTest(y::Real, vars::Expr...)::Bool
global x = y
for var in vars
if eval(var)
return true
end
end
return false
end
This works, but the appearance of global suggests the existence of a better way of obtaining the same goal. And that's my question: create a function with arguments a number and a list of Expr's. Such function returns true if any condition is satisfied and false otherwise.
This looks like a you are probably looking into using a macro:
macro genExpr(a::Real, b::Real)
quote
x-> x < $(a + b) && x > $(a - b)
end
end
function applyTest(y::Real, vars::Function...)::Bool
any(var(y) for var in vars)
end
Testing:
julia> e1 = #genExpr(0,3)
#15 (generic function with 1 method)
julia> e2 = #genExpr(8,2)
#17 (generic function with 1 method)
julia> applyTest(0,e1,e2)
true
However, with this simple code a function just generating a lambda would be as good:
function genExpr2(a::Real, b::Real)
return x-> x < (a + b) && x > (a - b)
end

Break Function without return

I have a function
function foo(a)
if a > 5
a = 5
end
some_more_code
end
If the if-statement is true I would like to end the function but I don't want to return anything - to change the value of a is all I need.
How do I do that?
You can write (note that I have also changed the syntax of function definition to make it more standard for Julia style):
function foo(a)
if a > 5
a = 5
return
end
# some_more_code
end
Just use the return keyword without any expression following it. To be precise in such cases Julia returns nothing value of type Nothing from a function (which is not printed in REPL and serves to signal that you did not want to return anything from a function).
Note though that the value of a will be only changed locally (within the scope of the function), so that outside of the function it will be unchanged:
julia> function foo(a)
if a > 5
a = 5
return
end
# some_more_code
end
foo (generic function with 1 method)
julia> x = 10
julia> foo(x)
julia> x
10
In order to make the change visible outside of the function you have to make a to be some kind of container. A typical container for such cases is Ref:
julia> function foo2(a)
if a[] > 5
a[] = 5
return
end
# some_more_code
end
foo2 (generic function with 1 method)
julia> x = Ref(10)
Base.RefValue{Int64}(10)
julia> foo2(x)
julia> x[]
5

How do I check if an array is empty in Julia?

I am trying to see if there's a handy way to check if an array in Julia is empty or not.
In Julia you can use the isempty() function documented here.
julia> a = []
0-element Array{Any,1}
julia> isempty(a)
true
julia> length(a)
0
julia> b = [1]
1-element Array{Int64,1}:
1
julia> isempty(b)
false
Note that I included the length check as well in case that will help your use case.
For arrays one can also simply use a == []. The types are ignored in this comparison (as usual).
julia> a = []
a == []
0-element Array{Any,1}
julia> a == []
true
julia> a == Int[]
true
julia> String[] == Int[]
true
From Julia help:
isempty determines whether a collection is empty (has no elements).
e.g.
julia> isempty([])
true
julia> isempty(())
true

Resources