// 1-15-Kotlin.kt import kotlin.math.abs import kotlin.math.sin // Kotlin has syntax that resembles languages such as // Java and C++, but it also has some important // differences. For example, the type follows the // variable name: // // x: Double // // Variables declared with 'var' may be modified, // while variables declared with 'val' may not. // mySin(x: Double): Double // // 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, ... fun mySin(x: Double): Double { if (!x.isFinite()) { return Double.NaN } var result = x var term = x var n = 2.0 while (true) { term *= -(x/n)*(x/(n + 1.0)) if (abs(term) < 1e-16) { break } result += term n += 2.0 } return result } fun main() { val x = 3.2 println("mySin(x): ${mySin(x)}") println("sin(x): ${sin(x)}") println("reference: ${-0.058374143427579909137}") println("mySin(Double.POSITIVE_INFINITY): " + "${mySin(Double.POSITIVE_INFINITY)}") }