Calculating square roots is a fundamental mathematical operation. In Kotlin, the sqrt function from the kotlin.math package provides a straightforward way to compute the square root of a given number.
Importing the Math Package
Before you can use the sqrt function in Kotlin, you need to import the kotlin.math package:
import kotlin.math.sqrtUsing the sqrt Function
The sqrt function takes a Double as an argument and returns the square root of that number as a Double. Here is a basic example:
fun main() {
val number = 25.0
val result = sqrt(number)
println("The square root of $number is $result")
}Running this code will output:
The square root of 25.0 is 5.0Handling Invalid Input
The sqrt function assumes a non-negative input. Calculating the square root of a negative number with this function will result in NaN (Not-a-Number). Here's an example:
fun main() {
val negativeNumber = -9.0
val result = sqrt(negativeNumber)
println("The square root of $negativeNumber is $result")
}This code snippet will output:
The square root of -9.0 is NaNCustom Function for Calculating Square Roots
If you need to handle both negative and positive inputs, you can write a custom function that provides a meaningful response. Here's a simple example:
fun safeSqrt(number: Double): Any {
return if (number >= 0) {
sqrt(number)
} else {
"Cannot calculate square root of a negative number"
}
}
fun main() {
val posResult = safeSqrt(16.0)
val negResult = safeSqrt(-16.0)
println("The square root of 16.0 is $posResult")
println(negResult)
}This code provides a more user-friendly response when dealing with negative inputs. It will output:
The square root of 16.0 is 4.0
Cannot calculate square root of a negative numberConclusion
Kotlin's sqrt function provides an easy way to compute square roots for non-negative numbers, making use of Kotlin's robust math library. By extending functionality with custom implementations, you can also tailor error handling to fit your particular needs.