Library contents

Kotlin kotlin.math.ln1p

In Kotlin, kotlin.math.ln1p computes the natural logarithm of 1 + x. It preserves precision for small x, where adding x to 1 can lose significant digits.

A simple example

kotlin.math.ln1p

  1. Start with 0
  2. Do this Find the natural log of 1 + 0
  3. Result 0
Adding one gives 1. The natural logarithm of 1 is zero.
Lesson.kt
fun main() {
    println(kotlin.math.ln1p(0.0))
}
Output
0.0

Syntax

Kotlin syntax
kotlin.math.ln1p(growth)
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Convert a small growth rate accurately

A dashboard measures a percentage change so small that rounding can hide it. Use a numerical operation designed for a change near zero to retain the information in the original reading.

From the programval growth = 0.01
Result0.010
Lesson.kt

fun main() {
    val growth = 0.01

    System.out.printf(java.util.Locale.ROOT, "%.3f%n", (kotlin.math.ln1p(growth)).toDouble())
}
Output
0.010

A one-percent increase gives a continuous rate of about 0.00995033, displayed to three decimal places.

Advertisements

Convert a small loss

A test signal loses two percent of its level. The analyst converts a fractional change into its continuous log change.

Given-0.02
Worked result-0.0202

Using -0.02 gives -0.0202 for this measurement.

Compare a small weekly increase

A greenhouse model records growth of half a percent. Its analyst uses the fractional increase directly to compute a stable log change.

Given0.005
Worked result0.0050

Using 0.005 gives 0.0050 for this measurement.

What to watch for

Pass the increase itself. Adding one before the call changes the calculation.

Documentation for kotlin.math.ln1p