Sling Academy
Home/Kotlin/Calculating Square Roots in Kotlin (`sqrt`)

Calculating Square Roots in Kotlin (`sqrt`)

Last updated: November 30, 2024

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.sqrt

Using 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.0

Handling 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 NaN

Custom 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 number

Conclusion

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.

Next Article: Finding Absolute Values in Kotlin (`abs`)

Previous Article: Performing Exponentiation in Kotlin (`pow`)

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin