A method called sine(), which takes as its only parameter a value of type double, and returns a value of type double. The parameter represents an angle expressed in radians, and the value returned by the method represents the trigonometric sine of this angle. For example, suppose the following method call is executed:
double sin = MyMath.sine(1.047197551);
After the execution of the above method call, the value stored in variable sin will be (approximately) 0.866025404, as the sine of 1.047197551 radians is approximately 0.866025404.
public class MyMath {
public static final double PI = 3.141592653589793;
public static double sine(double rad) {
while (rad < -PI || rad > PI) {
if (rad < -PI) {
rad += 2 * PI;
} else {
rad -= 2 * PI;
}
}
double res = 0;
double error = 1E-10;
for (int i = 1, j = 0; i <= 21; i += 2, j++) {
long fact = 1;
for (int k = 1; k <= i; k++) {
fact *= k;
}
double cur = res + (j % 2 == 0 ? 1 : -1) * (Math.pow(rad, i) / fact);
if (Math.abs(cur - res) < error) {
res = cur;
break;
}
res = cur;
}
return res;
}
public static void main(String[] args) {
System.out.println(sine(1.047197551));
}
}
Comments
Leave a comment