Skip to content

Instantly share code, notes, and snippets.

@0racle
Created September 9, 2025 06:10
Show Gist options
  • Select an option

  • Save 0racle/a7500851a2edbc68fe4a87b0955a392d to your computer and use it in GitHub Desktop.

Select an option

Save 0racle/a7500851a2edbc68fe4a87b0955a392d to your computer and use it in GitHub Desktop.
Kap Atan2

array/src/commonMain/kotlin/com/dhsdevelopments/kap/builtins/math_functions.kt

class Atan2APLFunction : APLFunctionDescriptor {
    class Atan2APLFunctionImpl(pos: FunctionInstantiation) : MathCombineAPLFunction(pos, resultType1Arg = ArrayMemberType.LONG) {

        override fun combine2Arg(a: APLSingleValue, b: APLSingleValue): APLValue {
            return numericRelationOperation(
                pos,
                a,
                b,
                { x, y -> atan2(y.toDouble(), x.toDouble()).makeAPLNumber() },
                { x, y -> atan2(y, x).makeAPLNumber() },
                { x, y -> ComplexFieldExtension.atan2(y, x).makeAPLNumber() },
                fnBigint = { x, y -> atan2(y.toDouble(), x.toDouble()).makeAPLNumber() },
                fnRational = { x, y -> atan2(y.toDouble(), x.toDouble()).makeAPLNumber() })
        }

        override fun combine2ArgLongToLong(a: Long, b: Long) = if (a < b) a else b
        override fun combine2ArgDoubleToDouble(a: Double, b: Double) = if (a < b) a else b

        override val optimisationFlags get() = OptimisationFlags(OPTIMISATION_FLAG_2ARG_LONG_LONG or OPTIMISATION_FLAG_2ARG_DOUBLE_DOUBLE)

        override val name2Arg get() = "atan2"
    }

    override fun make(instantiation: FunctionInstantiation) = Atan2APLFunctionImpl(instantiation)
}

mpmaths/src/commonMain/kotlin/com/dhsdevelopments/mpmaths/kotlin-complex.kt

// object ComplexFieldExtension {
    fun atan2(p: Complex, q: Complex): Complex {
        val p_re = p.re
        val p_im = p.im
        val q_re = q.re
        val q_im = q.im
        return Complex(atan2(p_re, q_re), atan2(p_im, q_im))
    }
// }

array/src/commonMain/kotlin/com/dhsdevelopments/kap/engine.kt

     registerNativeFunction("atan2", Atan2APLFunction(), "math")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment