Learning Kotlin Programming
Handy Kotlin Edge Case Numerical Handling
It's handy to learn about Infinity, and NaN (Not a Number) of Kotlin when programming with calculation
Coming from a traditional C programmer era when I started learning to program, calculations like the below will result in a crash, as they are not handled by the compiler well.
float result1 = somevalue/zero;
float result2 = sqrt(negativeValue);
It is normal for programmers back in those days to ensure we try-catch them or manually handle them e.g. to avoid zero, always return a very small number.
Discovery of Infinity and NaN
Recently, I explored a smooth curvy line graph plotting algorithm, where I need to calculate some slope using
dydx = (x2-x1)/(y2-y1).
When we have y2-y1
, there’s a possibility of getting 0, which might crash this equation (x2-x1)/(y2-y1)
when apply to old C programming.
But to my surprise, there weren’t any clashes even though I don’t try-catch them or special handle them.
Then I realize when I have y2-y1
that result in 0, the (x2-x1)/(y2-y1)
, not only didn’t crash the program but instead…