I’ve just tried to solve the Space Age exercise, researching how does Lua handle floating point numbers, and what methods are available to parse them to a fixed length.
My proposed solution got me close, but wasn’t quite right:
After looking at the community solutions, I found that the correct answer is to parse the number to a string using string.format("%.2f"), and then back to a number.
This was surprising to me as it’s very counter-intuitive. I tried with JavaScript as I’m more familiar with that language and a similar solution, using toFixed(2) also yields the same result.
So I was just wondering: is there some “algorithm” at play here that I can look into when having to work with floating number precision? I don’t know if “algorithm” is the right word to use in this context. I’m looking for a more general concept that talks about what’s going on behind the scenes here.
Wouldn’t it be a good idea to update the expected result in the test suite? It just seems more “correct” to follow the mathematical approach in this case, than jumping through hoops to achieve a particular result.
But I guess this also forces you to learn about this topic, which is the whole point Anyway, I’ll look more into this. Thanks for the help!
The data in the tests comes directly from the shared problem specifications repo which is shared across all tracks. The practice exercises try to stick to the shared data most of the time.
Some tracks do check for approximate equality within about 0.01 of the expected value (I’m in this camp personally). It’s up to the maintainer how they want to implement Space Age for their particular exercise. There are pros and cons to either approach, but Lua’s approach here does surface something a student may not have noticed had the test suite only checked for approximate equality. Then a student can follow up with their own research, submit a mentoring request, or ask here on the forums. Hopefully, they come out of it hopefully knowing a little more than they did before.
Come to think about it, Python might also want to include an obligatory link to 0.3000000000000000.com in that addendum to help explain why we ask for specific rounding, similar to the way we include number handling links in our introduction to the numbers concept exercise.
The TL;DR is that we ask for rounding so that we don’t have to fiddle with the floating point as much. (although rounding is a whole different matter if the student doesn’t use round(), and chooses another method that is not bankers rounding … but I am getting way off topic)
… So an addendum could also say directly that “we ask you round to x number of decimal places here, to avoid issues with floating point math” (with a link to 0.3000000000000000.com).
That is indeed the upside of that. Although, a different exercise where this is mentioned explicitly would have the same effect, wouldn’t it? I’m only bringing this up because I did spend a couple of hours banging my head against the wall