Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a cubic root in Kotlin?

Tags:

kotlin

in kotlin there is an internal math library and I only find the square root but there is no cubic root.

cubic root

import kotlin.math.sqrt
import kotlin.math.pow

fun Formule(a:Int):Double{
    //no working
    //rs = a.pow(1/3)
    //function
    retun rs
}

fun main(args: Array<String>){
    val calc = Formule(9)
}
like image 284
royer Avatar asked Dec 17 '22 17:12

royer


2 Answers

There's no need to use Java libraries, just use the Kotlin one:

import kotlin.math.pow

fun formula(a:Int):Double {
    return a.toDouble().pow(1/3.toDouble())
}

Just tested it:

println(formula(9)) //2.080083823051904

println(formula(27)) //3.0
like image 161
Louis Avatar answered Jan 05 '23 23:01

Louis


If you don't need Kotlin multi-platform support, the Java standard library has Math.cbrt(), which can be called safely from Kotlin.

val x: Double = Math.cbrt(125.0) // 5.0
like image 41
Todd Avatar answered Jan 05 '23 22:01

Todd