Advertisement
VyaraG

ComparingFloats

Nov 28th, 2014
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.84 KB | None | 0 0
  1. using System;
  2. //Write a program that safely compares floating-point numbers (double) with precision eps = 0.000001. Note that we cannot directly compare two floating-point numbers a and b by a==b because of the nature of the floating-point arithmetic. Therefore, we assume two numbers are equal if they are more closely to each other than a fixed constant eps. Examples:
  3.  
  4. //Number a  Number b    Equal (with precision eps=0.000001) Explanation
  5. //5.3   6.01    false   The difference of 0.71 is too big (> eps)
  6. //5.00000001    5.00000003  true    The difference 0.00000002 < eps
  7. //5.00000005    5.00000001  true    The difference 0.00000004 < eps
  8. //-0.0000007    0.00000007  true    The difference 0.00000077 < eps
  9. //-4.999999 -4.999998   false   Border case. The difference 0.000001 == eps. We consider the numbers are different.
  10. //4.999999  4.999998    false   Border case. The difference 0.000001 == eps. We consider the numbers are different.
  11.  
  12.  
  13. class ComparingFloats
  14. {
  15.     static void Main()
  16.     {
  17.         Console.Write("Enter a number: ");
  18.         double a = double.Parse(Console.ReadLine());
  19.         Console.Write("Enter a number: ");
  20.         double b = double.Parse(Console.ReadLine());
  21.  
  22.         double eps = 0.000001;
  23.  
  24.         if (a > b)
  25.         {
  26.             if (a - b > eps)
  27.             {
  28.                 Console.WriteLine("The two numbers are not equal with precision 0.000001");
  29.             }
  30.             else
  31.             {
  32.                 Console.WriteLine("The two numbers are equal with precision 0.000001");
  33.             }
  34.         }
  35.         else if (b < a)
  36.         {
  37.             if (b - a > eps)
  38.             {
  39.                 Console.WriteLine("The two numbers are not equal with precision 0.000001");
  40.             }
  41.             else
  42.             {
  43.                 Console.WriteLine("The two numbers are equal with precision 0.000001");
  44.             }
  45.         }
  46.  
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement