I am trying to do a really basic loop that creates a sequence of functions using an iterative process. I used an earlier version of Mathematica many years ago and thought this worked. Any help would be appreciated.
Here's the basic idea applied to the function g(x)=x. I keep getting error of Recursion depth of 256 exceeded. It also doesn't show a plot.
g[x_] := x;
For[i = 1, i < 4, i++,
f1[x_] := .25*g[2*x] + .25*2*x;
f2[x_] := .25*g[2*x - 1] - .25*(2*x - 1) + .25;
g[x_] := If[0 <= x <= .5, f1[x], f2[x]]
];
Plot[g[x], {x, 0, 1}, PlotRange -> {{0, 1}, {0, 1}}]
You want to Plot some point x,g[x].
Ok, need to figure out what g[x] is.
Ok, that happens to be f1[x].
Ok, need to figure out what f1[x] is.
That is defined to be g[x].
Ok, need to figure out what g[x] is.
Ok, that happens to be f2[x].
Ok, need to figure out what f2[x] is.
That is defined to be g[x].
And this happens over and over until Mathematica's check for runaway recursion stops it.
So describe very very clearly to yourself what your sequence of functions is supposed to be.
From that think carefully about how to turn that into Mathematica code without infinite recursion.
Related
Just playing around with Julia (1.0) and one thing that I need to use a lot in Python/numpy/matlab is the squeeze function to drop the singleton dimensions.
I found out that one way to do this in Julia is:
a = rand(3, 3, 1);
a = dropdims(a, dims = tuple(findall(size(a) .== 1)...))
The second line seems a bit cumbersome and not easy to read and parse instantly (this could also be my bias that I bring from other languages). However, I wonder if this is the canonical way to do this in Julia?
The actual answer to this question surprised me. What you are asking could be rephrased as:
why doesn't dropdims(a) remove all singleton dimensions?
I'm going to quote Tim Holy from the relevant issue here:
it's not possible to have squeeze(A) return a type that the compiler
can infer---the sizes of the input matrix are a runtime variable, so
there's no way for the compiler to know how many dimensions the output
will have. So it can't possibly give you the type stability you seek.
Type stability aside, there are also some other surprising implications of what you have written. For example, note that:
julia> f(a) = dropdims(a, dims = tuple(findall(size(a) .== 1)...))
f (generic function with 1 method)
julia> f(rand(1,1,1))
0-dimensional Array{Float64,0}:
0.9939103383167442
In summary, including such a method in Base Julia would encourage users to use it, resulting in potentially type-unstable code that, under some circumstances, will not be fast (something the core developers are strenuously trying to avoid). In languages like Python, rigorous type-stability is not enforced, and so you will find such functions.
Of course, nothing stops you from defining your own method as you have. And I don't think you'll find a significantly simpler way of writing it. For example, the proposition for Base that was not implemented was the method:
function squeeze(A::AbstractArray)
singleton_dims = tuple((d for d in 1:ndims(A) if size(A, d) == 1)...)
return squeeze(A, singleton_dims)
end
Just be aware of the potential implications of using it.
Let me simply add that "uncontrolled" dropdims (drop any singleton dimension) is a frequent source of bugs. For example, suppose you have some loop that asks for a data array A from some external source, and you run R = sum(A, dims=2) on it and then get rid of all singleton dimensions. But then suppose that one time out of 10000, your external source returns A for which size(A, 1) happens to be 1: boom, suddenly you're dropping more dimensions than you intended and perhaps at risk for grossly misinterpreting your data.
If you specify those dimensions manually instead (e.g., dropdims(R, dims=2)) then you are immune from bugs like these.
You can get rid of tuple in favor of a comma ,:
dropdims(a, dims = (findall(size(a) .== 1)...,))
I'm a bit surprised at Colin's revelation; surely something relying on 'reshape' is type stable? (plus, as a bonus, returns a view rather than a copy).
julia> function squeeze( A :: AbstractArray )
keepdims = Tuple(i for i in size(A) if i != 1);
return reshape( A, keepdims );
end;
julia> a = randn(2,1,3,1,4,1,5,1,6,1,7);
julia> size( squeeze(a) )
(2, 3, 4, 5, 6, 7)
No?
So I've combed through the various websites pertaining to Julia JuMP and using functions as arguments to #objective or #NLobjective, but let me try to state my problem. I'm certain that I'm doing something silly, and that this is a quick fix.
Here is a brief code snippet and what I would like to do:
using juMP;
tiLim = 1800;
x = range(1,1,M); # M stated elsewhere
solver_opt = "bonmin.time_limit=" * "$tiLim";
m = Model(solver=AmplNLSolver("bonmin",[solver_opt]));
#variables m begin
T[x];
... # Have other decision variables which are matrices
end
#NLobjective(m,:Min,maximum(T[i] for i in x));
Now from my understanding, the `maximum' function makes the problem nonlinear and is not allowed inside the JuMP objective function, so people will do one of two things:
(1) play the auxiliary variable + constraint trick, or
(2) create a function and then `register' this function with JuMP.
However, I can't seem to do either correctly.
Here is an attempt at using the auxiliary variable + constraint trick:
mymx(vec::Array) = maximum(vec) #generic function in Julia
#variable(m, aux)
#constraint(m, aux==mymx(T))
#NLobjective(m,:Min,aux)
I was hoping to get some assistance with doing this seemingly trivial task of minimizing a maximum.
Also, it should be noted that this is a MILP problem which I'm trying to solve. I've previously implemented the problem in CPLEX using the ILOG script for OPL, where this objective function is much more straightforward it seems. Though it's probably just my ignorance of using JuMP.
Thanks.
You can model this as a linear problem as follows:
#variable(m, aux)
for i in x
#constraint(m, aux >= T[i]
end
#objective(m, Min, aux)
I am working with a large computational fluid dynamics (finite difference) code which simulates forming solar systems. It is written in fortran and uses a 3D cylindrical grid to flux conserved quantities (mass, momentum, ...). I did not write the code, but use it to perform research. I am currently performing data analysis on output files, and I am having some trouble finding multiple local maximums in a 3D density array.
I first tried to use the basic maxloc and maxval intrinsic functions:
print*, maxloc(array)
print*, maxval(array)
This only provided me with the value of the first maximum encountered. I am looking for over-densities within the array that could be the precursors to forming planetesimals. I need to find them all, their locations, and then perform more analysis to find their "edge" within the grid, and integrate to find the total mass in each over-dense region. First things first, though. I need to find all the local maxima.
I found these two discussions, but neither seemed to solve the problem:
1) FORTRAN - MAXLOC which returns all positions of maximum values in array?
2) Finding [index of] the minimal value in array which satisfies a condition in Fortran
Using information in the first discussion, I tried to write my own multiple maxima finder, but only managed to do what the intrinsic functions do.
temp=0.0
do L = 0, LMAX-1
do K = 0, KMAX-1
do J = 0, JMAX-1
if (array(j,k,l)>=temp) then
temp = array(j,k,l)
tempj = j
tempk = k
templ = l
end if
end do
end do
end do
I also tried:
temp(j,k,l)=0.0
do L = 0, LMAX-1
do K = 0, KMAX-1
do J = 0, JMAX-1
if (array(j,k,l).gt.maxval(array)) then
temp(j,k,l) = array(j,k,l)
print*, temp(j,k,l), j,k,l
else
go to 20
end if
end do
end do
end do
20 continue
hoping it would skip the first maxima, and go on to the next. This did not work either, but I now see the flaw in my logic. I am now thinking that I can use maxloc(array) to find the j,k,l location of the first maxima, then write a loop which begins at that j,k,l index to find the next maxima, and continue in this way until I've found them all. I think this brute force method should work, but it seems clunky and computationally wasteful.
I am a physicist before I am a programmer. I was just hoping that someone could point me to a more elegant way of doing this. It seems really simple, so I am wondering why there is no intrinsic function which can already do this.
Thanks for the help.
After a long search on google I couldn't find a clear answer of this:
In Prolog doing recursion by itself its easy. My main problem is understanding where to place accumulators and counters. Here is an example:
nXlist(N,X,[X|T]):-
N \=0,
N1 is N-1,
nXList(N1,X,T).
nXList(0,_,[]).
media([X|L], N, Soma):-
media(L, N1, Soma1),
N is N1 + 1,
Soma is Soma1 + X.
media([], 0, 0).
On the first example i used a counter BEFORE the recursion but in the second example I use it AFTER. The reason I have done that is the called try and see cause i really can't understand why sometimes is before and sometimes is after...
Maybe the central point of your question is in the preamble:
In Prolog doing recursion by itself its easy
It's not easy, it's mandatory. We don't have loops, because we don't have a way to control them. Variables are assign once.
So, I think the practical answer is rather simple: if the 'predicate' (like is/2) needs a variable value, you ground the variable before calling it.
To me, it helps to consider a Prolog program (a set of clauses) as grammar productions, and clause arguments as attributes, either inherited (values computed before the 'instruction pointer') or synthesized (values computed 'here', to be returned).
update: Most importantly, if the recursive call is not last, the predicate is not tail recursive. So, having anything after the recursive call should be avoided if possible. Notice that both definitions in the answer by user false are tail recursive, and that's precisely due to the fact that the arithmetic conditions there are placed before the recursive call, in both of them. That's so basic, that we have to make an effort to notice it explicitly.
Sometimes we count down, sometimes we count up. I discuss this in another answer at length. It talks of accumulators, befores and afters. :)
There's also this thing called "associativity" of an operation (say, +), where
a+(b+(c+....)) == (a+b)+(c+...)
that lets us regroup and (partially) calculate sooner rather than later. As soon as possible, but not sooner.
Short answer: you can place such arithmetical relations both before and thereafter. At least, if you are using constraints in place of (is)/2. The only difference may be in termination and errors.
So let's see how your predicates can be defined with constraints:
:- use_module(library(clpfd)).
nXList(0,_,[]).
nXList(N,X,[X|T]):-
N #> 0,
N1 #= N-1,
nXList(N1,X,T).
media([], 0, 0).
media([X|L], N, Soma):-
N #> 0,
N #= N1 + 1,
Soma #= Soma1 + X,
media(L, N1, Soma1).
You can now use these definitions in a much more general way, say:
?- nXList(3, X, T).
T = [X, X, X]
; false.
?- media(Xs, 3, S).
Xs = [_A, _B, _C], _D+_A#=S, _C+_B#=_D
; false.
... nXList/3 can be more compactly expressed by:
..., length(T, N), maplist(=(X), T), ...
Suppose I wish to define a recursive function theta whose functionality should be apparent below.
The following definition will work.
theta[0] = 0;
theta[i_ ] := theta[i-1] + 1
However, this will not work.
theta[0] = 0;
theta[i_ + 1] := theta[i] + 1
My question is, is it possible to make something like the second definition work, where I can define the function based on the i+1 term instead of the i term?
I understand that they are mathematically equivalent, but I am curious about whether Mathematica will permit something like the second syntax.
It is perfectly feasible to make your second definition work if you understand that default automatic simplifications are done, often before you can get control, and if you then use your definition with appropriate parameters that match your definition.
Example
In[1]:= theta[i_ + 1] := Sin[i]+1;
theta[a + 1]
Out[2]= 1+Sin[a]
but then you probably expect to use this as
In[3]:= theta[8]
Out[3]= theta[8]
and that fails because you defined a function that matches the sum of something and one, but gave it just an integer and you have no definition that matches that. Even this fails
In[4]:= theta[7 + 1]
Out[4]= theta[8]
because the default automatic rules turn the sum of two integers into an integer and you are back to the previous case.
It is sometimes said that Mathematica does "structural" matching, if two structure of two expressions match the Mathematica accepts this as a match. This is very different from the sort of matching that anyone with a bit of mathematical maturity would use. A decade or more ago someone wrote up an article in the Mathematica Journal showing that it would be possible to use a more mathematical version of matching within Mathematica. I think that was completely ignored and nothing more was ever done with that. It would be nice if someone with the skill needed could bring that code up to the current version of Mathematica, but I think this might be a substantial challenge.
There is always "a way". For example:
ClearAll[a];
a[i_] = a[i] /. First#RSolve[{a[i + 1] == a[i] + 1, a[0] == 0}, a[i], i]