Experimenting with a sequence of complex numbers in Kotlin

The challenge

Consider the sequence S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n) where z is a complex number and n a positive integer (n > 0).

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

Experiment with S(n, z) to guess the domain of convergence Dof S and lim value when z is in D.

Then determine the smallest integer n such that abs(S(n, z) - lim) < eps where eps is a given small real number and abs(Z) is the modulus or norm of the complex number Z.

Call f the function f(z, eps) which returns n. If z is such that S(n, z) has no finite limit (when z is outside of Df will return -1.

Examples:

I is a complex number such as I * I = -1 (sometimes written i or j).

f(0.3 + 0.5 * I, 1e-4) returns 17

f(30 + 5 * I, 1e-4) returns -1

Remark:

For languages that don’t have complex numbers or “easy” complex numbers, a complex number z is represented by two real numbers x (real part) and y (imaginary part).

f(0.3, 0.5, 1e-4) returns 17

f(30, 5, 1e-4) returns -1

Note:

You pass the tests if abs(actual - exoected) <= 1

The solution in Kotlin

Option 1:

package solv

private fun modul(x: Double, y: Double): Double {
    if (x != 0.0 || y != 0.0)
        return Math.sqrt(x * x + y * y)
    else
        return 0.0
}
fun f(x: Double, y: Double, eps: Double): Int {
    if (modul(x, y) >= 1.0)
        return -1
    return (Math.log(eps) / Math.log(modul(x, y))).toInt()
}

Option 2:

package solv

import kotlin.math.*

fun f(x: Double, y: Double, eps: Double): Int {
    val m = hypot(x, y)
    return if (m < 1) log(eps, m).toInt() else -1
}

Option 3:

package solv

fun f(x: Double, y: Double, eps: Double): Int {
    val res = Math.log(eps) / Math.log(Math.hypot(x, y))
    return if (res < 0) -1 else res.toInt()
}

Test cases to validate our solution

package solv

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

class solvTest {
    private fun dotest(x:Double, y: Double, eps: Double, expect: Int) {
        val merr = 1.0
        println("Testing " + x + " " + y + " " + eps)
        val actual = f(x, y, eps)
        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() {
        dotest(0.64, 0.75, 1e-12, 1952)
        dotest(0.3, 0.5, 1e-4, 17)
        dotest(30.0, 50.0, 1e-4, -1)
        
    }
}
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments