The following class contains a method that should calculate the integral using the callback technique.
package integrals;
import java.lang.*;
public class Integrals
{
public static double f1(double x)
{
return x*5+Math.sin(x);
}
public static double f2(double x)
{
return Math.pow(x*f1(-x),x);
}
public static double TrapezoidalIntegration(double a,double b,int n,double (*f)(double))
{
double rValue=0;
double dx;
dx=(b-a)/n;
for(double i=f(a);i<f(b);i+=dx)
rValue+=((f(i)+f(i+dx))*dx)/2.0;
return rValue;
}
public static void main(String[] args)
{
}
}
How to make a callback in this case? I prefer to avoid ☞such solution☜ due to it's complexity and ugliness. Even if it is the least painful, I don't have an idea how to implement it here.
How to make a callback in this case? I prefer to avoid such solution due to it's complexity and ugliness. Even if it is the least painful, I don't have an idea how to implement it here.
Since there are no function pointers in Java, you have to use a common interface instead. Your functions then have to be implementations of that interface. It is up to you whether you want to use names for those implementing classes (i.e. class F1 extends Function { … }
) or anonymous classes instead (i.e. new Function { … }
). It is also up to you whether you write the imp0lementation inside that class, or instead have the class implementation call one of your existing static functions.
Taking one example, with anonymous classes directly containing the implementation:
public class Integrals
{
public interface Function {
double eval(double x);
}
public static final Function f1 = new Function() {
public double eval(double x) {
return x*5+Math.sin(x);
}
};
public static final Function f2 = new Function() {
public double eval(double x) {
return Math.pow(x*f1.eval(-x),x);
}
};
public static double TrapezoidalIntegration(double a,double b,int n,Function f)
{
// … using f.eval(x) to compute values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With