im begginer in C# and programming in general and i want to ask. I'm trying to make a project with datagridview in it and some calculations. Basicly what i want to do is from table of empirical data aproximate the data with chebyshev aproximation. Using code from numerical recipes i want to use this fuction, chebft and it looks like this:
void chebft(NRREAL a, NRREAL b, NRREAL c[], int n, NRREAL (*func)(NRREAL))
{
int k,j;
NRREAL fac,bpa,bma,*f;
f=vector(0,n-1);
bma=NR_1_2*(b-a);
bpa=NR_1_2*(b+a);
for (k=0;k<n;k++) {
NRREAL y=cos(NR_PI*(k+NR_1_2)/n);
f[k]=(*func)(y*bma+bpa);
}
fac=NR_2/n;
for (j=0;j<n;j++) {
NRZEAL sum=NR_0;
for (k=0;k<n;k++)
sum += f[k]*cos(NZ_PI*j*(k+NZ_1_2)/n);
c[j]=fac*(NRREAL)sum;
}
free_vector(f,0,n-1);
}
and i want it to use in C# so what i have so far:
public void chebft(double a, double b, double[] c, int n, double func)
{
int k,j;
double fac, bpa, bma;
double PI = 3.14159265358979323846;
Vector f = new Vector(0, n - 1);
bma = 0.5 * (b - a);
bpa = 0.5 * (b - a);
for (k = 0; k < n; k++)
{
double y = Math.Cos(PI*(k+0.5)/n);
f[k] = (func)(y*bma+bpa);
}
fac = 2.0 / n;
for (j = 0; j < n; j++)
{
double sum = 0.0;
for (k = 0; k < n; k++)
{
sum += f[k] * Math.Cos(PI * j * (k + 0.5) / n);
c[j] = fac * (double)sum;
}
}
}
I know there are mistakes in that func part and f[k] part, but i dont know how to fix them.
Thanks for help
The translation appears to be relatively solid with one exception (leaving aside possible numeric issues that require some more advanced knowledge of the problem to diagnose):
The function pointer
funcaccepts a double-valued parameter and returns a double. To pass such a lambda function in C#, which is essentially equivalent to a function pointer in C++, use the following form:You can then call the function as follows:
More information can be found here.
Also note that you do not need to cast
sumto a double in the final loop, as it already is a double, and that theMathclass already defines the constantMath.PI.