Which X for That Sum in Kotlin


The challenge

Consider the sequence U(n, x) = x + 2x**2 + 3x**3 + .. + nx**n where x is a real number and n a positive integer.

When n goes to infinity and x has a correct value (ie x is in its domain of convergence D), U(n, x) goes to a finite limit m depending on x.

Usually given x we try to find m. Here we will try to find x (x real, 0 < x < 1) when m is given (m real, m > 0).

Let us call solve the function solve(m) which returns x such as U(n, x) goes to m when n goes to infinity.

Examples:

solve(2.0) returns 0.5 since U(n, 0.5) goes to 2 when n goes to infinity.

solve(8.0) returns 0.7034648345913732 since U(n, 0.7034648345913732) goes to 8 when n goes to infinity.

Note:

You pass the tests if abs(actual - expected) <= 1e-12

The solution in Kotlin code

Option 1:

package solv

fun solve(m:Double):Double {
  val s = Math.sqrt(4 * m + 1)
  return (2 * m + 1 - s) / (2 * m)
}

Option 2:

package solv

import kotlin.math.sqrt

fun solve(m: Double): Double = 1 + (0.5 - sqrt(0.25 + m)) / m

Option 3:

package solv

fun solve(s:Double):Double {
  return (1 - Math.sqrt(4 * s + 1)) / (2.0 * s) + 1;
}

Test cases to validate our solution

package solv

import org.junit.Assert.*
import org.junit.Test
import java.util.Random

class solvTest {
  private fun assertFuzzy(m:Double, expect:Double) {
    val merr = 1e-12
    println("Testing " + m)
    val actual = solve(m)
    println("Actual: " + actual)
    println("Expect: " + expect)
    val inrange = Math.abs(actual - expect) <= merr
    if (inrange == false)
    {
      println("Expected must be near " + expect + ", got " + actual)
    }
    println("-")
    assertEquals(true, inrange)
  }
  @Test
  fun test1() {
    assertFuzzy(2.00, 5.000000000000e-01)
    assertFuzzy(4.00, 6.096117967978e-01)
    assertFuzzy(5.00, 6.417424305044e-01)
    
  }  
}