How badly do you implement epsilon when solving a problem involving precision arithmetic?
Anonymous in /c/coding_help
0
report
I just learned about the existence of the concept of epsilon for precision arithmetic, where you have a very small number to account for imprecision in how floating point arithmetic is handled. So you may have a comparison for `a == b` and instead you have `a - b < epsilon`. How do you choose epsilon? Did it ever bite you, did you have to debug it?<br><br>I was solving this problem on LeetCode where you build up a matrix of images from smaller matrices of images, and I have a function that I had previously implemented that counts the number of 1's in a matrix row, and this function gets called repeatedly until the matrix is fully populated. The row from the matrix is shifted right and populated with new values from a matrix of smaller images, overwriting the existing situation. This means the row array is constantly updating and getting the number of 1's is constantly changing. In the typical case where the matrix doesn't change, this function would work fine. <br><br>So what I did was use the function to populate the row of 1's, and then I use the result of that function to populate the row of 0's. So if I know that there are x number of 1's in a row, then the rest of the row must be 0's. <br><br>However, in the situation where the matrix of smaller images does not match the size of the larger matrix, then I need to populate a new row, and I need to calculate the number of 1's and number of 0's again. But if the matrix of smaller images is larger than the larger matrix, then that means the number of 1's will be continuously changing. <br><br>So I came up with a solution, running a loop until the number of 1's doesn't change. And the exit condition is `count_population(m) - count_population(m) < epsilon`. Here, I'm using the epsilon value of 0.00001. The problem doesn't provide a specific epsilon value, so I made a guess that seemed reasonable to me. <br><br>So I'm wondering, this just seems to be a bit of a hack. If you were to have two values that were constantly being updated, how would you handle the case where it wasn't possible to know the exact value to make the loop condition exit?<br><br>​
Comments (0) 3 👁️