Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Main()
- {
- // for any pair of comparisons, there are numbers
- // for which they give different results
- var a = 5.0000005m;
- var b = 5.0000006m;
- Console.WriteLine(CompareRound(a, b)); // false
- Console.WriteLine(ComparePrecision(a, b)); // true
- Console.WriteLine(CompareScaleFloor(a, b)); // true
- Console.WriteLine(CompareDelta(a, b)); // true
- a = 5.0000001m;
- b = 5.0000002m;
- Console.WriteLine(CompareRound(a, b)); // true
- Console.WriteLine(ComparePrecision(a, b)); // true
- Console.WriteLine(CompareScaleFloor(a, b)); // true
- Console.WriteLine(CompareDelta(a, b)); // true
- }
- // do the numbers round to the same number
- bool CompareRound(decimal a, decimal b)
- {
- return Math.Round(a, 6) ==
- Math.Round(b, 6);
- }
- // do the first X significant digits coincide
- bool ComparePrecision(decimal a, decimal b)
- {
- return (float)a == (float)b;
- }
- // do the first X digits after the decimal point coincide
- bool CompareScaleFloor(decimal a, decimal b)
- {
- return Math.Floor(a * 1000 * 1000) ==
- Math.Floor(b * 1000 * 1000);
- }
- // is the absolute difference lower than delta
- bool CompareDelta(decimal a, decimal b)
- {
- return Math.Abs(a - b) < 0.000001m;
- }
Advertisement
Add Comment
Please, Sign In to add comment