I am having trouble with this problem. Can someone show me their code and JavaDo
ID: 3890416 • Letter: I
Question
I am having trouble with this problem. Can someone show me their code and JavaDoc it to help me understand better. I am using Eclipse (Java) to code. Thnaks!
1st Part: Write a program, TaylorSeries, that implements two methods one for calculating sin(x) and one for calculating cos(x) using the Taylor series expansion. The method signatures should be:
public static double sin(double x)
public static double cos(double x)
For this problem use only while loops. Terminate calculation when the term, (-1)nx2n+1(2n+1)! and (-1)nx2n(2n)!respectively, reaches 0.
The Taylor series for sin(x) and cos(x) can be found here: Commonly Used Taylor Series.
Hint: You can compare your results against the methods Math.cos(x) and Math.sin(x) from the Math library.
2nd Part: Add two additional methods to the program TaylorSeries:
public static double sin(double x, int numIterations)
public static double cos(double x, int numIterations)
That calculate the sin and cos of x up to a given number of iterations specified as input parameter. For this methods use only for loops.
Explanation / Answer
/**
*
* @author Sam
*/
public class TaylorSeries {
private static long factorial(int x) {
long k = 1;
for (int i = 1; i <= x; i++)
k *= i;
return k;
}
public static double sin(double x) {
double sum = x;
int n = 1;
double term = x;
int sign = 1;
while (Math.abs(term) > 0) {
n += 2;
sign *= -1;
term = Math.pow(x,n)/factorial(n);
sum += sign*term;
}
return sum;
}
public static double cos(double x) {
double sum = 1;
int n = 0;
double term = 1;
int sign = 1;
while (Math.abs(term) > 0) {
n += 2;
sign *= -1;
term = Math.pow(x,n)/factorial(n);
sum += sign*term;
}
return sum;
}
public static double sin(double x, int numIterations) {
double sum = x;
int n = 1;
double term;
int sign = 1;
for (int i = 0; i < numIterations; i++) {
n += 2;
sign *= -1;
term = Math.pow(x,n)/factorial(n);
sum += sign*term;
}
return sum;
}
public static double cos(double x, int numIterations) {
double sum = 1;
int n = 0;
double term;
int sign = 1;
for (int i = 0; i < numIterations; i++) {
n += 2;
sign *= -1;
term = Math.pow(x,n)/factorial(n);
sum += sign*term;
}
return sum;
}
//TEST
public static void main(String[] args) {
System.out.println("Sin pi/6 = " + sin(3.14/6) + " or " + Math.sin(3.14/6));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.