Advertisement
dimipan80

2. Safely_Comparing_Floats

Jun 1st, 2014
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.90 KB | None | 0 0
  1. /* Write a program that safely compares floating-point numbers (double) with precision
  2.  * eps = 0.000001. Note that we cannot directly compare two floating-point numbers a and b
  3.  * by a==b because of the nature of the floating-point arithmetic.
  4.  * Therefore, we assume two numbers are equal if they are more closely
  5.  * to each other than a fixed constant eps. */
  6.  
  7. namespace _13.ComparingFloats
  8. {
  9.     using System;
  10.  
  11.     public class SafelyComparingFloats
  12.     {
  13.         private const double EPS = 0.000001d;
  14.  
  15.         public static void Main(string[] args)
  16.         {
  17.             checked
  18.             {
  19.                 Console.Write("Enter the First real number: ");
  20.                 double numA = double.Parse(Console.ReadLine());
  21.                 Console.Write("Enter the Second real number: ");
  22.                 double numB = double.Parse(Console.ReadLine());
  23.  
  24.                 if (!double.Equals(numA, numB))
  25.                 {
  26.                     if (numA < 0 && numB < 0)
  27.                     {
  28.                         numA = Math.Abs(numA);
  29.                         numB = Math.Abs(numB);
  30.                     }
  31.                    
  32.                     double difference = Math.Abs(numA - numB);
  33.                     if (difference < EPS)
  34.                     {
  35.                         Console.WriteLine("These two Float-Point numbers IS EQUALS !");
  36.                         Console.WriteLine("The Difference is too small: {0:F8} !", difference);
  37.                     }
  38.                     else
  39.                     {
  40.                         Console.WriteLine("These two Float-Point numbers is NOT EQUALS !");
  41.                         Console.WriteLine("The Difference is: {0} !", difference);
  42.                     }
  43.                 }
  44.                 else
  45.                 {
  46.                     Console.WriteLine("These two Float-Point numbers IS EQUALS !");
  47.                 }
  48.             }
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement