Taylor Series in Java Using float
I am implementing a method berechneCosinus(float x, int ordnung) in Java that should approximate the cosine of x using the Taylor series up to the specified order.
My questions:
Can I optimize the computation inside the method, without changing the signatures, in order to exactly match the given test results?
Here is what I have so far:
public class Taylor {
public float berechneFak(float x) {
if (x <= 1) return 1.0f;
int n = Math.round(x);
float fak = 1.0f;
for (int i = 2; i <= n; i++) {
fak *= i;
}
return fak;
}
public float berechneCosinus(float x, int ordnung) {
float pi = 3.14159265f;
float zweiPi = 2.0f * pi;
x = x % zweiPi;
if (x > pi) x -= zweiPi;
else if (x < -pi) x += zweiPi;
if (ordnung == 0) return 0.0f;
int anzahlTerme = (ordnung + 1) / 2;
float summe = 0.0f;
float term = 1.0f;
for (int i = 0; i < anzahlTerme; i++) {
int n = i * 2;
if (i > 0) {
term *= -x * x / ((n - 1) * n);
}
summe += term;
}
return summe;
}
}
This is the assignment:
public class Taylor {
public float berechneFak(float x) {
// insert code here!
// drandenken: Vorlesung!
return 0.0f;
}
public float berechneCosinus(float x, int ordnung) {
float acc = 0.0f;
// Ihr Code hierher!
return acc;
}
}
Testfälle , Erwartet / Erhaltenes Ergebnis
I implemented the cosine calculation method using the Taylor series and normalized x to the interval [−π,π]. However, the results slightly differ from the expected values in some test cases. Since I’m not allowed to change the method signatures and can only work with floats, I’m looking for tips on how to improve the accuracy.
Here is an Minimal Reproducible Example
public class Taylor {
public float berechneCosinus(float x, int ordnung) {
if (ordnung == 0) return 0.0f;
float sum = 0.0f;
float term = 1.0f;
for (int i = 0; i < (ordnung + 1) / 2; i++) {
int n = 2 * i;
if (i > 0)
term *= -x * x / ((n - 1) * n);
sum += term;
}
return sum;
}
public static void main(String[] args) {
Taylor t = new Taylor();
float x = 3.14159265f; // approx. PI
System.out.printf("%.6f\n", t.berechneCosinus(x, 13));
System.out.printf("%.6f\n", t.berechneCosinus(x, 14));
}
}
The actuall Output is:
-0.999900
-0.999900
The expected Output should be:
-0.999899
-0.999899
I'm aware of the limitations with floating point, the problem is that the tests check for exactly -0.999899, I'm wondering if it's possible to restructure the calculation to get the expected result. nonetheless I'm gonna ask my Prof. could be also possible that there is an error/mistake in the testingcode.
- 19
- 1
- 5