- Go Standard Library Cookbook
- Radomír Sohlich
- 175字
- 2021-06-24 18:56:38
How it works...
The first approach for the floating-point numbers comparison without the use of any built-in package (steps 1-5) requires the use of a so-called EPSILON constant. This is the value chosen to be a sufficient small delta (difference) between two numbers to consider the values as equal. The delta constant could be on the order of 1e-8, which is usually sufficient precision.
The second option is more complex, but also more useful for further work with floating-point numbers. The package math/big offers the Float type that could be configured for a given precision. The advantage of this package is that the precision could be much higher than the precision of the float64 type. For illustrative purposes, the small precision values were used to show the rounding and comparison in the given precision.
Note that the da and db numbers are equal when using the precision of 16-bits and not equal when using the precision of 32-bits. The maximal configurable precision can be obtained from the big.MaxPrec constant.