# Definite integral calculation in C#

How do I better calculate the definite integral? I am using a function to integrate and another to find the factorial recursively.

I'l like to better the algorithm or the efficiency or even the accuracy for that matter.

``````    public static double testStatistic(double meanTreatmentSumOfSquares, double meanErrorSumOfSquares)
{
return (meanTreatmentSumOfSquares / meanErrorSumOfSquares);
}

public static double pValue(double fStatistic, int degreeNum, int degreeDenom)
{
double pValue = 0;
pValue = integrate(0, fStatistic, degreeNum, degreeDenom);

return pValue;

}

public static double integrate(double start, double end, int degreeFreedomT, int degreeFreedomE)
{
int iterations = 100000;
double x, dist, sum = 0, sumT = 0;
dist = (end - start) / iterations;
for (int i = 1; i <= iterations; i++)
{
x = start + i * dist;
sumT += integralFunction(x - dist / 2, degreeFreedomT, degreeFreedomE);
if (i < iterations)
{
sum += integralFunction(x, degreeFreedomT, degreeFreedomE);
}
}
sum = (dist / 6) * (integralFunction(start, degreeFreedomT, degreeFreedomE) + integralFunction(end, degreeFreedomT, degreeFreedomE) + 2 * sum + 4 * sumT);
return sum;
}

public static double integralFunction(double x, int degreeFreedomT, int degreeFreedomE)
{
double temp=0;
temp = ((Math.Pow(degreeFreedomE, degreeFreedomE / 2) * Math.Pow(degreeFreedomT, degreeFreedomT / 2)) / (factorial(degreeFreedomE / 2 - 1) * factorial(degreeFreedomT / 2 - 1))) * (factorial(((degreeFreedomT + degreeFreedomE) / 2 - 1)))*((Math.Pow(x, degreeFreedomE / 2 - 1)) / (Math.Pow((degreeFreedomT + degreeFreedomE * x), ((degreeFreedomE + degreeFreedomT) / 2))));
return temp;
}

public static double factorial(double n)
{
if (n == 0)
{
return 1.0;
}
else
{
return n * factorial(n - 1);
}
}
}
}
``````
-
There is no question here, only a task. Focus on a specific part and then a specific question related to it. –  pst Jul 25 '12 at 7:28
Have you considered caching the factorial calculation? –  ANeves Jul 25 '12 at 15:39

## migrated from stackoverflow.comJul 25 '12 at 12:15

This question came from our site for professional and enthusiast programmers.