double sin = MathAssignment.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. sine of an angle x, denoted sin x, can be calculated using the following algorithm
• If x < -π, repeatedly add 2π to x until -π ≤ x ≤ π. Conversely, if x > π, repeatedly subtract 2π from x until -π ≤ x ≤ π. You MUST use 3.141592653589793 as a value for π.
. The last term in this sum, tn, will be the first term whose absolute value is less than 10 -10 2. A method called absoluteValue, which takes as its only parameter a value of type double, and returns a value of type double. The parameter represents an arbitrary number, and the value returned by the method represents the absolute value of this arbitrary number. The absolute value of a number x, denoted |x|, is x if x is greater than or equal to 0, and -x if x is less than 0. double value MathAssignment.absoluteValue(-42.0);
public class MathAssignment {
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 (absoluteValue(cur - res) < error) {
res = cur;
break;
}
res = cur;
}
return res;
}
public static double absoluteValue(double value) {
return value < 0 ? value * -1 : value;
}
public static void main(String[] args) {
System.out.println(sine(1.047197551));
}
}
Comments
Leave a comment