Forcing a WolframCloud Function to Evaluate - wolfram-language

I'm using sandbox.open.wolframcloud.com. I define a function f[x] which should return the successor of x, for example f[1] should return 2. However, I get f[1] as output. I've read about Evaluate[] however it does not seem to help:
In[5]:= f[x] := Evaluate[x+1]
In[7]:= Evaluate[f[1]]
Out[7]= f[1]
What am I doing wrong here?

There's no need for Evaluate. When defining functions in the Wolfram Language, you've gotta use an underscore after your argument name.
f[x_] := x+1;
That's because it needs x to be a pattern to match against. Otherwise the language just treats x as a symbol. For more info see this page on defining function in the Wolfram Language.

Related

SciPy optimize over vector indeterminate

I want to define a function as follows:
def f(x,m):
return np.exp(((x[i]-m).T)#((x[i]-m))
where the input is a known dataset array x, for example
x = np.array([[1,2],[3,4]])
but also an unknown 2d vector m.
At the moment I cannot define properly this function, since I get the ERROR:
NameError: name 'm' is not defined
The truth is I don't know what is the correct way to define m. Should it be something like
m = []
maybe? I know that unlike mathematica, I need to tell something to Python regarding m but it is not clear to me what.
Most importantly, I am interested in adding all components of x and minimizing the logarithm of f(x,m) to find the value of m for which f(x,m) is minimum.
To minimize a function you can use the scipy.optimize.minimize function link.
This might help you in understanding how to work with this function
import numpy as np
from scipy.optimize import minimize
def f(m, x, i):
return np.exp(((x[i]-m).T)#((x[i]-m)))
x = np.array([[1,2],[3,4]])
i = 0
m = minimize(f, x0=(0,0), args=(x, i)).x
I changed the order of parameters of your function f. minimize expects the first parameter to be the "variable" parameter which in this case is m, x and i are kept constant during the optimization.
In the call of the minimize function, x0 is the initial guess of m which is important to give because it tells the minimize function the shape of m. args is used to input the "constant" parameters.
The function returns an OptimizeResult where now the x attribute is the best estimate for m. However, the OptimizeResult contains some more useful information about the optimization.

"Private" symbols for sum(), diff(), or integrate()

Let's consider the following function I've already mentioned in my previous question:
rot[i](f) := sum(sum(sum(sum(
G[r,i]*G[q,j]*W[i,j,k]*('diff(f[k], y[q]) + sum(K[k,q,m]*f[m], m, 1, N)),
r, 1, N),
j, 1, N),
k, 1, N),
q, 1, N) $
It kind of works in general, but what if original expression f already contains symbols r, j, and so on? In this case it doesn't do the right thing. The only solution I've found so far is to use some unique prefix for these symbols or at least start their names with underscores: r → __r, j → __j. But I hope there should be a more idiomatic solution. Is there anything?
Unfortunately, in Maxima all symbols are effectively global -- the x in some expression is the same symbol as the x in f(x) := .... So there is no general way to ensure that function arguments are distinguished from other symbols of the same name. Some functions attempt to make their arguments local, e.g., sum treats the index variable specially, but integrate does not.
I made an attempt to make a lexical block construct which would make it possible to distinguish symbols of the same name. It is called blex and I think a web search should find it, if not, let me know and I'll post a link.

Iteratively Modifying a Function in C

I'm trying to create a numerical root finder in C, to find the zeros of Bessel Functions. Mathematical functions, F(x), can be deflated, by dividing the function by (x-x0), where x0 is a known root. The resulting function G(x) = F(x)/(x-x0), has all roots that F(x) had except at x0. This is useful as it prevents the same root being found twice by the solver.
When I find a root using my solver it is written to the array Roots[].
The Bessel Function is defined in math.h as double j0(double x).
I want to iteratively modify double j0(double x) so that I can have:
double my_j0(double x) = j0(x)/(x-Roots[n]);
I can then call this new, deflated function in my solver.
The above syntax doesn't make sense, but I don't know how to represent it.
I attempted to use a function pointer and defined
double (*my_j0)(double);
my_j0 = &j0;
But now I don't know how to iteratively modify the function, each time dividing by the root I found with my solving algorithm.
Thanks for the help!
you could pass it as an argument in a recursive function with a starting case. Something like this might work if your trying to solve iterativley.
double my_j0(double x, double my_root){
if(//some base case){
//final calculation
return calculation
}
if(my_root == some_initialization){
//do initial calculation work
my_root = calculated_root;
}
else{
//do calculations using your root
my_root = calculated_root;
}
return my_j0(x, my_root)
After more experience, I've realized what I was really looking for was an Anonymous Function or lambda function. A great introduction as to what a lambda function is can be found on this SO question.
Unfortunately, C does not support lambda functions, however, there are language extensions supported by both GCC (using macros) and Clang compilers for implementing lambda functions which can be found on Wikipedia.

How to write "good" Julia code when dealing with multiple types and arrays (multiple dispatch)

OP UPDATE: Note that in the latest version of Julia (v0.5), the idiomatic approach to answering this question is to just define mysquare(x::Number) = x^2. The vectorised case is covered using automatic broadcasting, i.e. x = randn(5) ; mysquare.(x). See also the new answer explaining dot syntax in more detail.
I am new to Julia, and given my Matlab origins, I am having some difficulty determining how to write "good" Julia code that takes advantage of multiple dispatch and Julia's type system.
Consider the case where I have a function that provides the square of a Float64. I might write this as:
function mysquare(x::Float64)
return(x^2);
end
Sometimes, I want to square all the Float64s in a one-dimentional array, but don't want to write out a loop over mysquare everytime, so I use multiple dispatch and add the following:
function mysquare(x::Array{Float64, 1})
y = Array(Float64, length(x));
for k = 1:length(x)
y[k] = x[k]^2;
end
return(y);
end
But now I am sometimes working with Int64, so I write out two more functions that take advantage of multiple dispatch:
function mysquare(x::Int64)
return(x^2);
end
function mysquare(x::Array{Int64, 1})
y = Array(Float64, length(x));
for k = 1:length(x)
y[k] = x[k]^2;
end
return(y);
end
Is this right? Or is there a more ideomatic way to deal with this situation? Should I use type parameters like this?
function mysquare{T<:Number}(x::T)
return(x^2);
end
function mysquare{T<:Number}(x::Array{T, 1})
y = Array(Float64, length(x));
for k = 1:length(x)
y[k] = x[k]^2;
end
return(y);
end
This feels sensible, but will my code run as quickly as the case where I avoid parametric types?
In summary, there are two parts to my question:
If fast code is important to me, should I use parametric types as described above, or should I write out multiple versions for different concrete types? Or should I do something else entirely?
When I want a function that operates on arrays as well as scalars, is it good practice to write two versions of the function, one for the scalar, and one for the array? Or should I be doing something else entirely?
Finally, please point out any other issues you can think of in the code above as my ultimate goal here is to write good Julia code.
Julia compiles a specific version of your function for each set of inputs as required. Thus to answer part 1, there is no performance difference. The parametric way is the way to go.
As for part 2, it might be a good idea in some cases to write a separate version (sometimes for performance reasons, e.g., to avoid a copy). In your case however you can use the in-built macro #vectorize_1arg to automatically generate the array version, e.g.:
function mysquare{T<:Number}(x::T)
return(x^2)
end
#vectorize_1arg Number mysquare
println(mysquare([1,2,3]))
As for general style, don't use semicolons, and mysquare(x::Number) = x^2 is a lot shorter.
As for your vectorized mysquare, consider the case where T is a BigFloat. Your output array, however, is Float64. One way to handle this would be to change it to
function mysquare{T<:Number}(x::Array{T,1})
n = length(x)
y = Array(T, n)
for k = 1:n
#inbounds y[k] = x[k]^2
end
return y
end
where I've added the #inbounds macro to boost speed because we don't need to check the bound violation every time — we know the lengths. This function could still have issues in the event that the type of x[k]^2 isn't T. An even more defensive version would perhaps be
function mysquare{T<:Number}(x::Array{T,1})
n = length(x)
y = Array(typeof(one(T)^2), n)
for k = 1:n
#inbounds y[k] = x[k]^2
end
return y
end
where one(T) would give 1 if T is an Int, and 1.0 if T is a Float64, and so on. These considerations only matter if you want to make hyper-robust library code. If you really only will be dealing with Float64s or things that can be promoted to Float64s, then it isn't an issue. It seems like hard work, but the power is amazing. You can always just settle for Python-like performance and disregard all type information.
As of Julia 0.6 (c. June 2017), the "dot syntax" provides an easy and idiomatic way to apply a function to a scalar or an array.
You only need to provide the scalar version of the function, written in the normal way.
function mysquare{x::Number)
return(x^2)
end
Append a . to the function name (or preprend it to the operator) to call it on every element of an array:
x = [1 2 3 4]
x2 = mysquare(2) # 4
xs = mysquare.(x) # [1,4,9,16]
xs = mysquare.(x*x') # [1 4 9 16; 4 16 36 64; 9 36 81 144; 16 64 144 256]
y = x .+ 1 # [2 3 4 5]
Note that the dot-call will handle broadcasting, as in the last example.
If you have multiple dot-calls in the same expression, they will be fused so that y = sqrt.(sin.(x)) makes a single pass/allocation, instead of creating a temporary expression containing sin(x) and forwarding it to the sqrt() function. (This is different from Matlab/Numpy/Octave/Python/R, which don't make such a guarantee).
The macro #. vectorizes everything on a line, so #. y=sqrt(sin(x)) is the same as y = sqrt.(sin.(x)). This is particularly handy with polynomials, where the repeated dots can be confusing...

Conditional checks for different variables

I have a function which sets a variable based on another variable.
if(!button_x.on)
button_x.on = 1;
if(!button_y.on)
button_y.on = 1;
if(!button_z.on)
button_z.on = 1;
.
.
.
If it is x, y, z, …. is determined only at runtime. Having multiple such conditions for various(100s) different cases does not look good. Is there a better way to go about this in C?
EDIT:
I should have better framed my example above.
if (!structureA.visited)
visit_structureA(); // does some operation
if (!structureB.visited)
visit_structureB();
if (!structureC.visited)
visit_structureC();
.
.
.
The number of structures and the name of the structure is not known at compile time. But the structure names follow a specific pattern shown above. It is known only at runtime.
I tried using macros something like:
#define VISIT(str) \
if (!structure##str.visited) \
visit_structure##str();
//In the function:
// str = 'known at runtime'
VISIT(str);
But this would not work for obvious reason that preprocessor directives are replaced during compile time and not runtime. I am not sure if there is a better way for this?
In your example, you set a variable value according to the same variable, not another one, if this is the case, and you want to change it from 0 to 1 and vice versa, you can do it without condition:
button_x.on = !button_x.on;
If you have many of those with the same idea of behavior, consider using array and itertating it.
In C, the following condition:
if (!x)
x = 1;
is equivalent to:
x = 1;
if the variable is boolean (on/off), which I assume is the case if we are talking about buttons.

Resources