Math

suggest change

Kotlin provides a comprehensive, multiplatform math library in the kotlin.math package. Unlike java.lang.Math, kotlin.math functions are idiomatic top-level functions and extension properties available seamlessly across Kotlin/JVM, Kotlin/JS, and Kotlin/Native without needing static class prefixes.

Importing the Math Library

To import all math functions and mathematical constants:

import kotlin.math.*

Mathematical Constants

The kotlin.math package provides the fundamental mathematical constants with full Double precision:

import kotlin.math.PI
import kotlin.math.E

fun main() {
    println("Pi: $PI") // 3.141592653589793
    println("Euler's constant e: $E") // 2.718281828459045
}

Basic Arithmetic and Rounding

Kotlin includes standard utility functions for absolute value, sign determination, rounding, and limits:

import kotlin.math.*

fun main() {
    // Absolute value and sign
    println(abs(-42))        // 42
    println(abs(-3.14))      // 3.14
    println(sign(-15.0))     // -1.0
    println(sign(0.0))       // 0.0

    // Rounding operations
    println(round(3.49))     // 3.0
    println(round(3.51))     // 4.0
    println(floor(3.99))     // 3.0 (largest integer <= value)
    println(ceil(3.01))      // 4.0 (smallest integer >= value)
    println(truncate(3.85))  // 3.0 (discards fractional part)
    println(truncate(-3.85)) // -3.0

    // Minimum and Maximum
    println(max(10, 25))     // 25
    println(min(5.2, 3.1))   // 3.1
}

Powers, Roots, and Exponential Functions

Kotlin provides pow as an extension function on Double and Float, alongside square and cube root calculations:

import kotlin.math.*

fun main() {
    // Exponentiation (Double.pow)
    val base = 2.0
    val exponent = 8.0
    val power = base.pow(exponent)
    println("2^8 = $power") // 256.0

    // Roots
    println("Square root of 81: ${sqrt(81.0)}") // 9.0
    println("Cube root of 27: ${cbrt(27.0)}")   // 3.0

    // Hypotenuse: sqrt(x^2 + y^2) without intermediate overflow
    val hypotenuse = hypot(3.0, 4.0)
    println("Hypotenuse of (3, 4): $hypotenuse") // 5.0

    // Logarithms and exponentials
    println("Natural log of e: ${ln(E)}")          // 1.0
    println("Log base 10 of 1000: ${log10(1000.0)}") // 3.0
    println("Log base 2 of 64: ${log2(64.0)}")       // 6.0
    println("Arbitrary base: ${log(81.0, 3.0)}")    // 4.0
    println("e^2: ${exp(2.0)}")                     // 7.38905609893065
}

Trigonometric Functions

Trigonometric functions expect angles in radians:

import kotlin.math.*

fun main() {
    val angleDegrees = 45.0
    val angleRadians = angleDegrees * (PI / 180.0)

    println("sin(45°): ${sin(angleRadians)}") // ~0.7071
    println("cos(45°): ${cos(angleRadians)}") // ~0.7071
    println("tan(45°): ${tan(angleRadians)}") // ~1.0

    // Inverse trigonometric functions
    val arcSin = asin(1.0) // PI / 2
    println("asin(1.0) in radians: $arcSin")
    println("asin(1.0) in degrees: ${arcSin * (180.0 / PI)}") // 90.0

    // Arc tangent 2 (atan2) for polar coordinate conversion
    val theta = atan2(1.0, 1.0)
    println("atan2(1, 1): $theta") // ~0.785398 (PI / 4)
}

Clamping Values with coerceIn

Kotlin standard library provides expressive extension methods on all comparable numerical types to clamp values within boundaries:

fun main() {
    val health = 150
    // Keep health between 0 and 100
    val clampedHealth = health.coerceIn(0, 100)
    println(clampedHealth) // 100

    val speed = -5
    val safeSpeed = speed.coerceAtLeast(0)
    println(safeSpeed) // 0

    val volume = 120
    val cappedVolume = volume.coerceAtMost(100)
    println(cappedVolume) // 100
}

Precise Financial Math: BigDecimal

Standard Double and Float IEEE 754 representations suffer from binary floating-point rounding errors (e.g., 0.1 + 0.2 != 0.3). When calculating financial or exact transactions, use java.math.BigDecimal with Kotlin's operator overloads:

import java.math.BigDecimal
import java.math.RoundingMode

fun main() {
    val price = BigDecimal("19.99")
    val taxRate = BigDecimal("0.0825")

    // Kotlin supports +, -, *, / operators natively on BigDecimal
    val tax = (price * taxRate).setScale(2, RoundingMode.HALF_UP)
    val total = price + tax

    println("Price: $$price") // $19.99
    println("Tax:   $$tax")   // $1.65
    println("Total: $$total") // $21.64
}

Bitwise Operations

For low-level algorithms, bit manipulation in Kotlin uses named infix functions rather than symbols:

fun main() {
    val a = 0b0011 // 3
    val b = 0b0101 // 5

    println(a and b)      // Bitwise AND: 0b0001 (1)
    println(a or b)       // Bitwise OR:  0b0111 (7)
    println(a xor b)      // Bitwise XOR: 0b0110 (6)
    println(a.inv())      // Bitwise Inversion (NOT)
    println(a shl 2)      // Signed Shift Left: 0b1100 (12)
    println(16 shr 2)     // Signed Shift Right: 4
    println(-16 ushr 2)   // Unsigned Shift Right
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents