This answer is valid for Java 7 or less that doesn't support closures nor callbacks.
First define an abstract class or an interface with a method that will calculate the integral value. For this sample, I'll define an interface:
interface IntegralCalculation {
double getIntegralValue(double x);
}
In your actual code, let's replace double (*f)(double)
parameter for the interface and the method to use:
public static double TrapezoidalIntegration(double a,double b,int n, IntegralCalculation integralCalc) {
double rValue;
double dx;
dx=(b-a)/n;
// for(int i=f(a);i
Now, in your main
method (or anywhere else where you will call this TrapezoidalIntegration
method), pass an implementation of the interface. You can pass an instance of a class that implements the interface or an anonymous class.
Example using a class instance of a class that implements the interface (sorry, don't know other way to say it):
class BasicFunction implements IntegralCalculation {
@Override
public double getIntegralValue(double x) {
return x*5+Math.sin(x);
}
}
public class Integrals {
public static void main(String[] args) {
double x = TrapezoidalIntegration(0, 10, 10, new BasicFunction());
}
}
Using an anonymous class:
public class Integrals {
public static void main(String[] args) {
double x = TrapezoidalIntegration(0, 10, 10, new IntegralCalculation() {
private double f1(double x) {
return x*5+Math.sin(x);
}
@Override
public double getIntegralValue(double x) {
return Math.pow(x*f1(-x),x);
}
});
}
}
From the code above:
- You can't pass a function pointer in Java, so
double (*f)(double)
parameter would be invalid, instead, we use an abstract class or an interface. IMO an interface would be better.
- Once you have designed the interface, it must have a method that satisfy the rules of your function pointer. In this case,
double (*f)(double)
means a method that has a double
as parameter and returns a double
value. This is handled by getIntegralValue
method.
After replacing the function pointer by the interface as parameter in TrapezoidalIntegration
method, you should call the getIntegralValue
as if it were the function pointer:
for(int i = integralCalc.getIntegralValue(a);
i < integralCalc.getIntegralValue(b); i += dx) { ... }