Advertisement
syssboxx

CompareFloatingPointWithPrecision

May 29th, 2013
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.70 KB | None | 0 0
  1. //Write a program that safely compares floating-point numbers with precision of 0.000001. Examples: (5.3 ; 6.01)  false;  (5.00000001 ; 5.00000003)  true
  2.  
  3. using System;
  4.  
  5. class CompareFloatingPointNumbers
  6. {
  7.     static void Main()
  8.     {
  9.        
  10.         decimal a = 5.3m;
  11.         decimal b = 6.01m;
  12.  
  13.         decimal a2 = 5.000000001m;
  14.         decimal b2 = 5.00000003m;
  15.  
  16.         decimal precision = 0.000001m;
  17.  
  18.         bool equalAB = Math.Abs(a - b) < precision;
  19.         Console.WriteLine("Are number {0} and {1} equal? {2}", a, b, equalAB);
  20.  
  21.         bool equalAB2 = Math.Abs(a2 - b2) < precision;
  22.         Console.WriteLine("Are number {0} and {1} equal? {2}", a2, b2, equalAB2);
  23.  
  24.  
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement