// 1-15-Java.java // // Java programs are organized into classes, and methods // such as mySin are members of those classes. // // The java.lang package, which contains Math and Double, // is automatically available and does not need to be // imported. public class Main { public static void main(String[] args) { double x = 3.2; System.out.println("Trig.mySin(x): " + Trig.mySin(x)); System.out.println("Math.sin(x): " + Math.sin(x)); System.out.println("reference: " + -0.058374143427579909137); System.out.println("Trig.mySin(Double.POSITIVE_INFINITY): " + Trig.mySin(Double.POSITIVE_INFINITY)); } } class Trig { // mySin(double x) // // Approximate sin(x) using the Taylor series // // x^3 x^5 x^7 // sin(x) = x - --- + --- - --- + ... // 3! 5! 7! // // Rather than calculating each power and factorial // separately, calculate each term from the previous // term: // // x^2 // next = -term -----------, // n(n + 1) // // where n takes the values 2, 4, 6, ... public static double mySin(double x) { if (!Double.isFinite(x)) { return Double.NaN; } double result = x; double term = x; for (double n = 2.0; ; n += 2.0) { term *= -(x/n)*(x/(n + 1.0)); if (Math.abs(term) < 1e-16) { break; } result += term; } return result; } }