I wrote this convenience function for testing if a...
# getting-started
l
I wrote this convenience function for testing if a double is within a range.
Copy code
fun assertWithin(expected: Double, actual: Double, tolerance: Double) {
    val message = "Difference of ${actual-expected} is out of range. " +
            "Expected $expected, got $actual"
    if(abs(expected-actual) > tolerance) println(message)
    assertTrue(abs(expected-actual) <= tolerance, message)
}
I see this message in the console, though
Copy code
Difference of -6.004799503160669E14 is out of range. Expected 0.75, got -6.004799503160661E14
How could (-6.004799503160661E14)-(0.75) be equal to (-6.004799503160661E14)? Edit: misread the exponent. subtracting 0.75 from 6*10^14 is essentially 6*10^14
k
What are you expecting (-6.004799503160661E14)-(0.75) to be equal to? Also, why not use an existing function from one of the many unit testing libraries? By the way, you are calculating the difference and creating the message before you know if it's needed or not, so if you're calling this function in a tight loop where performance could be an issue, you might want to create the message inside the
if
block.
1
l
This is in unit tests, so I don’t see performance as critical.
I just realized that the exponent is +14, not -14
They’re not anywhere near the same order of magnitude, so subtracting 0.75 has essentially no effect.
k
If you're using kotlin.test, you can use [assertEquals with tolerance](https://kotlinlang.org/api/latest/kotlin.test/kotlin.test/assert-equals.html). If you're using another library, it will almost certainly have an equivalent function that takes a tolerance.
l
I was not aware of that. I’ll take a look.