Hallo zusammen,
ich verzweifel derweil an einem algorithmus der mir fast das gleiche Ergebnis liefern soll wie die Math.exp() funktion. Ich komme einfach nicht weiter meine Ergebnisse stimmen einfach nicht. Nur für die, ersten 3 zahlen ungefähr also 1,0 ; 2,0 ; 3,0 passt es.
Ich würde mich um Hilfe sehr freuen oder hinweise was an meinem Algorithmus falsch ist. Danke schoneinmal!
Mein Code:
Liebe Grüße
Lee
ich verzweifel derweil an einem algorithmus der mir fast das gleiche Ergebnis liefern soll wie die Math.exp() funktion. Ich komme einfach nicht weiter meine Ergebnisse stimmen einfach nicht. Nur für die, ersten 3 zahlen ungefähr also 1,0 ; 2,0 ; 3,0 passt es.
Ich würde mich um Hilfe sehr freuen oder hinweise was an meinem Algorithmus falsch ist. Danke schoneinmal!
Mein Code:
Code:
public class ExpTaylor {
public static void main(String[] args) {
// Variables
double x;
double epsilon;
// Scanner to read Variables from the shell
Scanner sc = new Scanner(System.in);
// User input
System.out.println("Please enter x: ");
x = sc.nextDouble();
System.out.println("Please enter epsilon: ");
epsilon = sc.nextDouble();
// Variables for the do while loop
int facu = 1; // start by 1 cause zero make no sense
int i = 1; // start by the value 1 cause we need it for the Faculty - calculation
double fX = 0;
double fZero = 0;
double terminate;
int facuX = 1;
int k = 2; // start by 2 cause of step further
double xRes = x;
do {
// Faculty calculation
facu = facu * i;
i++;
// + 1 addition for fX and fZero
if (facu == 1) {
fZero = (1) + (x) / (facu);
fX = (1) + (x) / (facu);
} else {
// Now without -> + 1
fZero = fZero + ((xRes * x) / (facu));
xRes = xRes * x;
}
// one calculation further + facuX
facuX = facuX * k;
k++;
fX = fX + ((xRes * x) / (facuX));
// termination
terminate = (fX - fZero) / (fZero);
} while (terminate > epsilon);
// Output
System.out.println(fX);
System.out.println(Math.exp(x));
sc.close();
}
}
Liebe Grüße
Lee