I need your help again.
I need to know how I can send any functions to my class in order that my method works.
For example, in the code below, I can send only log function. But I would like to send any expressions as a function. Did I clear?
Thanks everyone for helping.
The class: package appMatematica;
import java.util.*;
public class Simpsons13 {
// Given function to be integrated
// Function to calculate f(x)
static float func(float x)
{
return (float)Math.log(x);
}
// Function for approximate integral
static float simpsons13(float ll, float ul,
int n)
{
// Calculating the value of h
float h = (ul - ll) / n;
// Array for storing value of x
// and f(x)
float[] x = new float[10];
float[] fx= new float[10];
// Calculating values of x and f(x)
for (int i = 0; i <= n; i++) {
x[i] = ll + i * h;
fx[i] = func(x[i]);
}
// Calculating result
float res = 0;
for (int i = 0; i <= n; i++) {
if (i == 0 || i == n)
res += fx[i];
else if (i % 2 != 0)
res += 4 * fx[i];
else
res += 2 * fx[i];
}
res = res * (h / 3);
return res;
}
}
THE MAIN:
package appMatematica;
import java.util.Scanner;
import appMatematica.Gauss;
import appMatematica.Simpsons38;
import appMatematica.Trapezios;
public class Principal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int op = 0;
System.out.println("Escolha qual operação quer realizar\n");
System.out.println("1-Trapézios \n2-Simpsons 3/8 \n3-Simpsons 1/3 \n4-Quadratura de GAUSS");
op = sc.nextInt();
if (op == 1) {
double x1;
double x2;
int i;
System.out.println("Digite o valor de x1\n");
x1 = sc.nextDouble();
System.out.println("Digite o valor de x2\n");
x2 = sc.nextDouble();
System.out.println("Digite o valor do intervalo\n");
i = sc.nextInt();
System.out.println(Trapezios.trapezio(x1, x2, i));
}
if (op == 2) {
float limite_inferior;
float limite_superior;
int i;
System.out.println("Digite o limite inferior\n");
limite_inferior = sc.nextFloat();
System.out.println("Digite o limite superior\n");
limite_superior = sc.nextFloat();
System.out.println("Digite o número de iterações\n");
i = sc.nextInt();
System.out.println(Simpsons38.calculate38(limite_inferior, limite_superior, i));
}
if (op == 3) {
float limite_inferior;
float limite_superior;
int i;
System.out.println("Digite o limite inferior\n");
limite_inferior = sc.nextFloat();
System.out.println("Digite o limite superior\n");
limite_superior = sc.nextFloat();
System.out.println("Digite o número de iterações\n");
i = sc.nextInt();
System.out.println(Simpsons13.simpsons13(limite_inferior, limite_superior, i));
}
}
}