Sling Academy
Home/Kotlin/Understanding `NaN` and Infinity in Kotlin

Understanding `NaN` and Infinity in Kotlin

Last updated: November 29, 2024

In programming, special numeric values such as NaN (Not-a-Number) and Infinity are used to deal with calculations that go beyond the conventional limitations of IEEE 754 floating-point arithmetic. In Kotlin, a modern statically typed programming language, these values are used in computations involving floating-point numbers. Understanding how to work with these values is crucial in building robust applications.

What is NaN?

NaN stands for 'Not-a-Number.' It is a special value used to represent results of operations that are undefined or unrepresentable. For example, if you divide zero by zero, the result is undefined, leading to NaN.

val result = 0.0 / 0.0
println(result) // Output: NaN

NaN values are contagious in arithmetic operations, meaning any operation involving NaN will yield NaN as a result.

val a = 0.0 / 0.0
val b = a + 1 // Still NaN
println(b) // Output: NaN

Comparing NaN

It is important to note that NaN is not equal to any value, including itself. To check if a variable is NaN, you should use the isNaN() function.

val notANumber = 0.0 / 0.0
println(notANumber == Double.NaN) // Output: false
println(notANumber.isNaN()) // Output: true

What is Infinity?

Infinity is another special floating-point value in Kotlin, representing a number that is infinitely large or small. You can obtain positive infinity by dividing a positive number by zero, and negative infinity by dividing a negative number by zero.

val positiveInfinity = 1.0 / 0.0
println(positiveInfinity) // Output: Infinity

val negativeInfinity = -1.0 / 0.0
println(negativeInfinity) // Output: -Infinity

Infinity behaves in a predictable manner. Adding or subtracting to infinity results in infinity, and infinity added to or subtracted from any finite number is still infinity.

val x = 5.0
val inf = 1.0 / 0.0
println(x + inf) // Output: Infinity
println(x - inf) // Output: -Infinity

Using Infinity and NaN

When writing functions that handle mathematical calculations, consider the possibility of encountering NaN or infinity, especially when the input values are coming from an untrusted source.

Here's a simple way to handle NaN:

fun safeDivide(a: Double, b: Double): Double {
    return if (b == 0.0) {
        throw IllegalArgumentException("Divisor cannot be zero")
    } else {
        a / b
    }
}

fun main() {
    println(safeDivide(1.0, 0.0)) // Will throw exception
}

Conclusion

Understanding NaN and Infinity in Kotlin is essential as they have direct implications in debug-ging floating-point calculations. Recognizing and correctly handling these values helps in developing safe and predictable Kotlin applications. Always be prepared for edge cases involving these special values to pre-vent unexpected behavior in your applications.

Next Article: Introduction to Booleans in Kotlin

Previous Article: How to Round Numbers in Kotlin

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