Completato esercizio p6.12 con Sequence
This commit is contained in:
parent
488aa8d04d
commit
dc16cd2e7a
|
@ -0,0 +1,37 @@
|
||||||
|
/**
|
||||||
|
Metodo che calcola e^x
|
||||||
|
@author radaelli11353
|
||||||
|
*/
|
||||||
|
public class ExpApprossimator implements Sequence<Double> {
|
||||||
|
private double term;
|
||||||
|
private double x;
|
||||||
|
private int n;
|
||||||
|
|
||||||
|
/**
|
||||||
|
Costruttore parametrico completo
|
||||||
|
@param x Valore a cui elevare e
|
||||||
|
*/
|
||||||
|
public ExpApprossimator(double x) {
|
||||||
|
term = 1;
|
||||||
|
this.x = x;
|
||||||
|
n = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
Metodo che calcola il valore successivo nella sequenza
|
||||||
|
@return Addendo successivo nella sequenza
|
||||||
|
*/
|
||||||
|
public Double next() {
|
||||||
|
term = term*x/n;
|
||||||
|
n++;
|
||||||
|
return term;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
Metodo che verifica se la precisione 1E-9 (arbitraria) è stata raggiunta
|
||||||
|
@return Vero o falso in base alle approssimazioni eseguite
|
||||||
|
*/
|
||||||
|
public boolean hasNext() {
|
||||||
|
return term > 1E-9;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
/**
|
||||||
|
Classe che esegue il test dell'uso della funzione ExpApprossimator
|
||||||
|
@author radaelli11353
|
||||||
|
*/
|
||||||
|
public class ExpTester {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Scanner in = new Scanner(System.in);
|
||||||
|
|
||||||
|
System.out.print("Inserisci il valore di x");
|
||||||
|
double x = in.nextDouble();
|
||||||
|
|
||||||
|
ExpApprossimator gen = new ExpApprossimator(x);
|
||||||
|
|
||||||
|
double sum = 1;
|
||||||
|
while(gen.hasNext()) {
|
||||||
|
sum += gen.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println(sum);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
public interface Sequence<T> {
|
||||||
|
public boolean hasNext();
|
||||||
|
public T next();
|
||||||
|
}
|
Loading…
Reference in New Issue