Iteratively Modifying a Function in C - 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.

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.

Solve systems of ODEs in Julia with initial condition as 2D array

http://diffeq.sciml.ai/latest/tutorials/ode_example.html
I am trying to use the ODE solver in Julia (DifferentialEquations.jl) to solve a system of n interacting particles. Let's say that the system is in 2D, and the equation of motion of each particle is described by a second-order ODE of its position with respect to time. Then four variables are needed for each particle, two for positions and two for velocities. Then 4n variables are needed to be declared. Is there a way to generalize, such that one does not need to list all 4n equations one by one?
For example:
http://diffeq.sciml.ai/latest/tutorials/ode_example.html#Example-2:-Solving-Systems-of-Equations-1
I try to modify the Lorenz equation in the link above a little bit to n particles (which is a very very rough attempt since I actually have no idea how to do it) by trying to extend u and du to 2D arrays.
using DifferentialEquations
using Plots
n = 4
function lorenz(du,u,p,t,i)
du[i,1] = 10.0*(u[i,2]-u[i,1])*sum(u[1:n,1])
du[i,2] = (u[i,1]*(28.0-u[i,3]) - u[i,2])*sum(u[1:n,1])
du[i,3] = (u[i,1]*u[i,2] - (8/3)*u[i,3])*sum(u[1:n,1])
end
u0 = hcat([1.0;0.0;0.0], [0.0;1.0;0.0], [0.0;0.0;1.0])
tspan = (0.0,100.0)
prob = ODEProblem(lorenz,u0,tspan)
sol = solve(prob)
This, without surprise, does not work, but I hope that you get the idea what I am trying to do. Is there anyway for the ODE solver to solve u as a 2D array (or other ways that can achieve similar purposes?)
The problem is not the 2D Array. For example replacing your lorenz definition with
function lorenz(du,u,p,t)
du[1,1] = 10.0*(u[1,2]-u[1,1])
du[1,2] = (u[1,1]*(28.0-u[1,3]) - u[1,2])
du[1,3] = (u[1,1]*u[1,2] - (8/3)*u[1,3])
end
will work.
The problem is the function signature, the additional i is not supported. If you want to solve a network of Lorenz oscillators you have to code it with a function with the same signature, e.g. lorenz_network!(du, u, p, t) for the inplace version. Put a loop over the individual oscillators in your function and you are almost there.

OCamlcstub performance

Does using multiple call to external functions written in C affects the performance of an OCaml program?
For instance, let's assume that I want to create a function which creates a float list using the previous value in the list to compute the next iteration. For some reason, I wish this function to come from a cstub.
Does it make any difference in term of performance whether I write everything in C or if I mix C external functions with my OCaml code?
I guess this question is related to what actually happens when compiling:
ocamlc -o hello.byte -c hello.cma cstub.o
Said differently, is there any material difference between doing:
external next_iter: float -> float = "next_iter"
let make_list n first_val =
let rec aux acc current_val n =
if n = 0 then (* I assume that n will never be <0 *)
acc
else
let new_val = next_iter current_val in
aux (new_val :: acc) new_val (n-1) in
aux [] first_val n
and
external make_list: float -> int -> float list = "make_list"
(* Full implementation in C *)
Side question, if my cstub looks like this:
#include <caml/mlvalues.h>
CAMLprim value add_3(value x)
{
int i = Int_val(x);
return Val_int(x+3);
}
Is the location of the returned value shared with the OCaml code or does OCaml reallocate a new part of the memory before using the value?
I am asking because I expect the second option to be especially inefficient when using the make_list solution from cstub.c for a large list (if it is implemented this way).
In general, calling a C function from OCaml has some small constant overhead. First of all, C calling conventions usually differ from the OCaml calling convention and are less efficient. When a C function is called, a compiler needs to store some registers that might be clobbered by the call, as well as it needs to restore them afterward. Also, if a C function allocates values in the OCaml heap (that is assumed by default) the call is wrapped by code that setups and clears garbage collector roots. If your function doesn't allocate, then you may mark its external specification with the [##noalloc] attribute to remove unnecessary GC setup. Finally, OCaml compiler can't inline (obviously) your external calls, so some optimization opportunities are missed, like code specialization and allocation elimination. To form this in numbers, the call wrapping code is usually about 10 extra assembly instructions. Thus if your C function is compatible in size, then the overhead might be significant, so you may consider either make the call non-allocatable or consider rewriting it in OCaml. But in general, C functions are much bigger thus the overhead is negligible. As a final note, OCaml is not Python and is very efficient, so there is rarely or never a need to reimplement some algorithm in C. The external interface is mostly used for calling existing libraries, that are not available in C; invoking system calls; calling high-performance mathematical libraries and so on.
Side question
Is the location of the returned value shared with the OCaml code or does OCaml reallocate a new part of the memory before using the value?
In your example, the returned value is an immediate value and it is stored in a CPU register, i.e., it is not allocated. Int_val and Val_int are simple macros that translate between the C int representation and the OCaml int representation, i.e., shifts a value to the left and sets the least significant bit.
But in general, if a value is allocated with caml_alloc and friends, then the value is allocated in the OCaml heap and is not copied (unless GC is performing moving for its own purposes).

How to check if variable is Scalar or Array before mxIsScalar was introduced?

In Matlab's mex files there is a function mxIsScalar that tells you if that input to the mex files is an scalar or not. But that function has been introduced in R2015a.
If using a previous version of Matlab (2014b in my case, if that matters), what is the most elegant way of checking if an input is an Scalar or an array?
Do I need to combine mxGetNumberOfDimensions, mxGetDimensions and mxIsNumeric to do it? Or is there any other clear and simple way of doing it? I favor readability over speed.
As well as mxGetM and mxGetN, there's also mxGetNumberOfElements, which you could use like so:
bool const isScalar = (size_t(1) == mxGetNumberOfElements(prhs[0]));
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if (mrows==1 && ncols==1) {
// Scalar prhs[0] here
}
Note that, if prhs[0] has more than 2 dimensions say N, then mxGetN is the result of product of dimensions 2 ... N. mxGetM will always return the first dimension. This may not be a good check for sparse matrices where these may not return the actual number of elements in the matrix.
A full example mex file can be found at http://www.mathworks.com/help/matlab/matlab_external/passing-a-scalar_btgcjh1-1.html.

Conjugate of a complex number in Matlab

In order to convert a Matlab code to C, I want to write it in a similar way to C first then its translation would become trivial.
I faced a problem with this line:
A = E*[SOLS' ; ones(1,10 ) ];
Where E is (9x4) real matrix and SOLS is (3x10) complex matrix. A should be a 9x10 complex matrix.
I translated this line as follows:
for i=1:9
for j=1:10
A(i,j)=E(i,1)*conj(SOLS(j,1))+E(i,2)*conj(SOLS(j,2))+E(i,3)*conj(SOLS(j,3))+ E(i,4);
end
end
I got the same result. When I replaced conj(X) by real(X)-i*imag(X)for example:
conj(SOLS(j,1)) by `real(SOLS(j,1))-imag(SOLS(j,1))*i`,
I got a wrong result and I don't understand why.
I'm doing this because in the C code, every complex number is represented by a struct with variable.re the real part and variable.im the imaginary part.
typedef struct COMPLEX{
float re;
float im;
}Complex;
I want to write a very similar matlab code to C to manipulate variables easily in C with getting a similar result with Matlab.
How to correct this please?
You are using i both as a looping index and sqrt(-1).
If you want to replace conj(SOLS(j,1)) use instead
real(SOLS(j,1))-imag(SOLS(j,1))*1i

Resources