Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kotlin sequence generator for stepping through float ranges without accumulating floating-point errors
fun generateSequenceOfFractions(
range: ClosedFloatingPointRange<Float>,
step: Float
): Sequence<Float> {
val multiplier = 1f / step
val start = floor(range.start * multiplier).toInt()
val endInclusive = ceil(range.endInclusive * multiplier).toInt()
return generateSequence(start) { it + 1 }
.takeWhile { it <= endInclusive }
.map{ it.toFloat() / multiplier }
}
@RunWith(AndroidJUnit4::class)
class FractionsSequenceTest {
@Test
fun testGenerateSequenceOfFractions() {
val fractions = generateSequenceOfFractions(-1000f..1000f, step = 0.1f)
.toList()
fractions.forEach {
assertThat(it).isAtLeast(-1000f)
assertThat(it).isAtMost(1000f)
}
assertThat(fractions).isInStrictOrder()
assertThat(fractions).hasSize(1000 * 2 * 10 + 1) // Don't forget the 0 in the middle!
assertThat(fractions).contains(100f)
assertThat(fractions).contains(500.1f)
assertThat(fractions).contains(500.2f)
assertThat(fractions).contains(0.2f)
assertThat(fractions).contains(0f)
assertThat(fractions).contains(-10f)
assertThat(fractions).contains(-10f)
assertThat(fractions).contains(-10.3f)
assertThat(fractions).doesNotContain(-10.31f)
assertThat(fractions).doesNotContain(0.35f)
assertThat(fractions).doesNotContain(0.31f)
assertThat(fractions).doesNotContain(-.35f)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment