Advertisement
Guest User

Problem 13.* Comparing Floats

a guest
Mar 21st, 2014
820
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.65 KB | None | 0 0
  1. namespace _13.ComparingFloats
  2. {
  3.     using System;
  4.     /*
  5.      * 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:
  6.         Number a    Number b    Equal (with precision eps=0.000001) Explanation
  7.         5.3 6.01    false               The difference of 0.71 is too big (> eps)
  8.         5.00000001  5.00000003  true    The difference 0.00000002 < eps
  9.         5.00000005  5.00000001  true    The difference 0.00000004 < eps
  10.         -0.0000007  0.00000007  true    The difference 0.00000077 < eps
  11.         -4.999999   -4.999998   false   Border case. The difference 0.000001 == eps. We consider the numbers are different.
  12.         4.999999    4.999998    false   Border case. The difference 0.000001 == eps. We consider the numbers are different.
  13.      */
  14.     class ComparingFloats
  15.     {
  16.         static void Main()
  17.         {
  18.             Console.Write("Enter first number : ");
  19.             double firstNumber = double.Parse(Console.ReadLine());
  20.  
  21.             Console.Write("Enter second number : ");
  22.             double secondNumber = double.Parse(Console.ReadLine());
  23.  
  24.             double difference = Math.Abs(firstNumber - secondNumber);
  25.  
  26.             double threshold = 0.000001; // doubles are equal if their difference is less than this value - you choose this value based on your needs
  27.             bool areEqual = difference < threshold;
  28.  
  29.             Console.WriteLine(areEqual);
  30.         }
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement