// 1-15-CSharp.cs using System; // C# has syntax similar to C++ and Java, but functions // are members of classes. Here, MySin is a static method // of the Trig class. class MainClass { public static void Main() { double x = 3.2; Console.WriteLine($"Trig.MySin(x): {Trig.MySin(x)}"); Console.WriteLine($"Math.Sin(x): {Math.Sin(x)}"); Console.WriteLine($"reference: {-0.058374143427579909137}"); Console.WriteLine( $"Trig.MySin(double.PositiveInfinity): " + $"{Trig.MySin(double.PositiveInfinity)}" ); } } 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; } }